gpt4 book ai didi

java - 在执行正确的代码后,如何阻止我的代码执行每个 println?

转载 作者:行者123 更新时间:2023-12-01 17:46:09 25 4
gpt4 key购买 nike

    Scanner scan = new Scanner(System.in);

System.out.print("Enter 2 numbers: ");
int num1 = scan.nextInt();
int num2 = scan.nextInt();
System.out.println("Numbers Saved! Choose your operator + - * / ");
String operator = scan.next();
int result;

result = (operator.equals("+")) ? (num1 + num2) : (num1);
System.out.println("The addition result is " +result);
result = (operator.equals("-")) ? (num1 - num2) : (num1);
System.out.println("The subtraction result is " +result);
result = (operator.equals("*")) ? (num1 * num2) : (num1);
System.out.println("The multiplication result is " +result);
result = (operator.equals("/")) ? (num1 / num2) : (num1);
System.out.println("The division result is " +result);



}

}这是我的简单计算器代码,例如,当我选择 + 选项时,它会运行所有 System.out.println 行,我如何防止它执行此操作并仅执行与运算符匹配的 println?

最佳答案

尝试切换:

switch (operator) {
case "+":
result = num1 + num2;
System.out.println("The addition result is " + result);
break;
case "-":
result = num1 - num2;
System.out.println("The subtraction result is " + result);
break;
case "-":
result = num1 * num2;
System.out.println("The multiplication result is " + result);
break;
case "/":
result = num1 / num2;
System.out.println("The integer division result is " + result);
break;
default:
throw IllegalArgumentException("Unsupported operator: " + operator);
}

关于java - 在执行正确的代码后,如何阻止我的代码执行每个 println?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55210906/

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