I am making a basic calculator, where it does addition, multiplication, etc. It first checks the type of operation it is eg, 1 is for addition, 2 for multiplication and so on. If it detects that the operation type input is invalid, it just simply tells me in the console an error. Is there any method I can use to detect the method, and then re-enter the input?
public void printCheck() throws ArithmeticException{
if (op == 2) {
System.out.println("You have chosen addition");
}
else if (op == 3) {
System.out.println("You have chosen subtraction");
}
else if (op == 4) {
System.out.println("You have chosen multiplication");
}
else if (op == 5) {
System.out.println("You have chosen division");
}
else {
throw new ArithmeticException("Entered an invalid operation");
}
try {
a.op(0);
}
catch(ArithmeticException e){
System.out.println("You have entered an invalid operation");
}
You may repeat the input of the operation code until it is valid.
I don't recommend using exceptions here because it's a common and well known case that the user gives an invalid input. Instead you should create a simple method isValidOperationCode
which checks the input. For improved readability I have removed the global variable op
and turned it into a local variable which gets passed as parameter into the methods which need it.
Example:
int op;
do {
op = askUserForOperation();
printCheckOperation(op);
} while (!isValidOperationCode(op));
with a modified printCheckOperation
method
...
} else if (op == 5) {
System.out.println("You have chosen division");
} else {
System.out.println("Entered an invalid operation");
}
and the new method
private boolean isValidOperationCode(int op) {
return 2 <= op && op <= 5;
}
I'm Sorry i couldn't be more elaborate since I'm using a mobile phone to answer to this question. I hope this answer helps.
public void printCheck(){
while(true){
if(op<2 || op>5){
enterNewOp();
}
else {
switch(op) {
case 2:
System.out.println("You have select addition");
case 3:
System...
case 4:
......
}
break;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.