我正试图通过将数字作为用户输入来执行算术运算,我想连续运行代码,直到用户拒绝为止。如果我想在用户输入为"n/n"后终止代码,我应该如何在该代码中编写"else"语句?
import java.util.*;
class FirstExample{
static void arithmetic(){
Scanner sc = new Scanner(System.in);
while(true){
System.out.println("nDo u want to perform the arithmetic operations? (Y/N): ");
String input = sc.nextLine();
if(input=="y"||input=="Y")
sc.nextLine();
System.out.println("Enter first number: ");
double first = sc.nextDouble();
System.out.println("Enter second number: ");
double second = sc.nextDouble();
System.out.println("Addition of the two number is: "+(first+second));
System.out.println("Subtraction of the two number is: "+(first-second));
System.out.println("Multiplication of the two number is: "+(first*second));
System.out.println("Division of the two number is: "+(first/second));
sc.nextLine();
}
}
public static void main(String[]args){
FirstExample.arithmetic();
}
}
```
//else{
// System.exit(0);
// }
//tried adding this block of code but it gets terminated even after giving 'y/Y'
if (!input.equalsIgnoreCase("y")) {
break;
}
这里有一些东西。
- 首先,如前所述,使用.equals((或.equalsIgnoreCase((来比较java中的字符串
- 其次,在循环中断时退出是这里最容易做的事情
- 第三,不需要其他语句,因为只有当你需要在这一点上停止时,你才感兴趣——否则你可以继续你正在做的事情
即使输入Y,它也会退出的原因是,比较String
和==
将不起作用,因为它比较的是对字符串的引用,而不是字符串中的字符。相反,使用.equals方法:
if(input.equals("y") || input.equals("Y"))
一个可能的解决方案是引入布尔标志。因此,与其使用while (true)
,不如将其重构为:
class FirstExample {
static void arithmetic() {
Scanner sc = new Scanner(System.in);
boolean shouldStop = false;
while(!shouldStop){
System.out.println("nDo u want to perform the arithmetic operations? (Y/N): ");
String input = sc.nextLine();
if ("n".equalsIgnoreCase(input)) {
shouldStop = true;
} else if ("y".equalsIgnoreCase(input)) {
sc.nextLine();
System.out.println("Enter first number: ");
double first = sc.nextDouble();
System.out.println("Enter second number: ");
double second = sc.nextDouble();
System.out.println("Addition of the two number is: "+(first+second));
System.out.println("Subtraction of the two number is: "+(first-second));
System.out.println("Multiplication of the two number is: "+(first*second));
System.out.println("Division of the two number is: "+(first/second));
sc.nextLine();
}
}
}
}
此外,还有两条评论(有些已经指出(:
- 使用
equals(String)
或equalsIgnoreCase(String)
(不区分大小写(而不是==
。equalsIgnoreCase
的一个例子可以在这里找到 - 您可以对字符串文字而不是变量调用
equals()
(或equalsIgnoreCase()
(;这是为了避免空指针异常。因此,如果input
是null
,则可以执行"n".equalsIgnoreCase(input)
,而不是执行input.equalsIgnoreCase("n)
。你可以在这个SO线程上阅读更多