我遇到了java if if语句嵌套在while循环中的问题

Aay*_*jan 2 java

我是初学者.

我正在尝试使用java while循环.我知道java while循环和if语句,但从未嵌套过它们.我将首先发布脚本,然后告诉你们这个问题.

这是脚本:

import java.util.Scanner;
class whileloop{
    public static void main(String args[]){
        Scanner scan = new Scanner(System.in);
    System.out.println("This is a basic calculator.");
    System.out.println("To exit, input exit when asked to input the method.");
    System.out.println("----------------------------------------------");
    while (true){
        System.out.println("to add, input '+', to subtract, input '-', to divide, input '/', to multiply, input '*' and to exit, input 'exit.'");
        System.out.println("----------------------------------------------------");
        System.out.print("Please enter a method here:");
        String method = scan.nextLine();
        if (method == "exit"){
            System.out.println("You chose to exit.");
            break;
        }
        else if (method == "+"){
            System.out.println("You chose to add.");
            System.out.print("Please enter first number here:");
            double fnum = scan.nextInt();
            System.out.print("Please enter second number here:");
            double snum = scan.nextInt();
            double ans = fnum + snum;
            System.out.print("The answer is");
            System.out.println(ans);
        }
    }
}
}
Run Code Online (Sandbox Code Playgroud)

首先,我不知道这种类型的嵌套我现在只是在试验,所以也许这就是为什么我的方法对你们来说似乎有点不寻常.

现在,问题是每当我执行这段代码时,无限循环工作完美但它总是跳过if语句,无论我输入什么并开始再次循环指令.

请帮我解决一下这个.

Pra*_*mar 5

使用

method.equalsIgnoreCase("exit")method == "exit"

equalsIgnoreCase比较内容但==比较引用,在您的情况下,引用将与您scan.nextLine();创建新的String对象时使用的引用不同.


npi*_*nti 5

比较字符串时,您需要使用该.equals()方法,因此,在您的情况下,您需要更改method == "exit"method.equals("exit").这同样适用于其他if声明.

您可以查看 Oracle教程,以获取有关字符串比较的更多信息.


Jon*_*lor 5

如果您使用==比较字符串,这将比较对象的引用,在这种情况下,它将始终返回false.如果您实际上没有看到这种情况,那么您没有其他地方而只有其他地方,并且它会继续进行下一次迭代.

将其更改为.equals()方法以比较对象值而不是引用.

边注

请注意参考比较,因为您可能已经看到了使用引用相等性的奇怪示例,这可能会引发您(这对我来说肯定是第一次,如下面的示例所示).

String a = "Hello";
String b = "Hello";
Run Code Online (Sandbox Code Playgroud)

如果你a == b在这种情况下比较它实际上将返回true,这是因为Java缓存字符串,因此它们在这种情况下具有相同的引用.当你看到这样的例子时要小心,因为它们是例外.