Switch statement question
Hi guys . what's up
Actually I have a question concernig switch statement that I tried to solve but I couldn't :(:(
The question is :
Write a program using switch case statement that simulates a calculator and that program will provide the basic integer arithmetic operations such as +, -, *, and /. The output of the program is shown as below:
Enter first number :4
Enter second number :5
CHOICE OF CALCULATION
'+' :plus
'-' :Minus
'*' :Multiply
'/' :division
Enter your choice :*
The answer is 20
Re: Switch statement question
Quick search in google gave me this
The switch Statement (The Java™ Tutorials > Learning the Java Language > Language Basics)
In the example above they switch an integer. In your case I would suggest creating char and switch it:
Code :
int firstNumber;
int secondNumber;
char operation;
//TODO: read character from the input
switch(operation) {
case '+':
System.out.println("The answer is" + (firstNumber + secondNumber));
break;
case '-':
System.out.println("The answer is" + (firstNumber - secondNumber));
break;
default:
System.out.println("Unknown operator used..");
break;
}
Re: Switch statement question
Actually I tried the code it didn't work properly~X(~X(
Re: Switch statement question
You asked how does switch operation work.
I explained it to you. However there are things you need to do yourself, you need to read firstNumber, secondNumber and operation character before you switch. I didn't do your whole asignement because it's YOURS job to do.
Take a look at this SwitchExample class I made.
Code :
public class SwitchExample {
public static void main(String[] args){
int firstNumber = 2;
int secondNumber = 1;
//you can change operation to + or -
char operation = '+';
switch(operation) {
case '+':
System.out.println("The answer is " + (firstNumber + secondNumber));
break;
case '-':
System.out.println("The answer is " + (firstNumber - secondNumber));
break;
default:
System.out.println("Unknown operator used..");
break;
}
}
}
Re: Switch statement question
Thaaanks for your help. And sorry for disturbing you Delisra, you know I'm still new in java progrmming
X_XX_XX_X
Re: Switch statement question