gpt4 book ai didi

java - 在java计算器中验证用户输入的问题

转载 作者:行者123 更新时间:2023-12-02 09:21:17 24 4
gpt4 key购买 nike

因此,我正在用 Java 编写计算器代码作为作业,我想在最后包含一个 else 语句,如果用户没有输入有效的运算符,则会收到错误消息。问题是,即使我输入有效的运算符,它也会打印结果,然后打印 else 错误消息。任何帮助,将不胜感激。


public class Main {

public static void main(String[] args){

Scanner inputi=new Scanner(System.in);
double num1,num2;
char operator;

System.out.println("Please enter the first number: ");
num1=inputi.nextDouble();
System.out.println("Please enter the second number: ");
num2=inputi.nextDouble();

Scanner oper=new Scanner(System.in);
System.out.println("Please enter the operator, the operators are +,-,*,/,%");
operator = oper.next().charAt(0);

if(operator== '+') {
System.out.println("The sum of these numbers is: "+(num1+num2));
}
if(operator=='-') {
System.out.println("The diff of these numbers is: "+ (num1-num2));
}
if(operator=='*') {
System.out.println("The result of this multiplication is: "+(num1*num2));
}
if(operator=='/') {
System.out.println("The division is: "+(num1/num2));
}
if(operator=='%') {
System.out.println("The module is: "+(num1%num2));
}
else {
System.out.println("Please just pick an operator..");

}
}

}

最佳答案

我建议使用 switch 来代替:

     switch (operator) {
case '+':
System.out.println("+");
break;
case '-':
System.out.println("-");
break;
/* Other operators */
default:
System.out.println("Please just pick an operator..");
}

关于java - 在java计算器中验证用户输入的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58676872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com