[英]Is there a way for me to re-enter a wrong input?
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. 我正在制作一个基本的计算器,在其中进行加法,乘法等。它首先检查它的运算类型,例如1是加法,2是乘法,依此类推。 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. 相反,您应该创建一个简单的
isValidOperationCode
方法来检查输入。 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. 为了提高可读性,我删除了全局变量
op
并将其转换为局部变量,该局部变量作为参数传递给需要它的方法。
Example: 例:
int op;
do {
op = askUserForOperation();
printCheckOperation(op);
} while (!isValidOperationCode(op));
with a modified printCheckOperation
method 使用修改后的
printCheckOperation
方法
...
} 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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.