简体   繁体   English

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

[英]I am facing problems with java if statement nested in while loop

I am a beginner. 我是初学者。

I am experimenting with java while loop. 我正在尝试使用java while循环。 I have knowledge of both java while loop and if statements but have never nested them before. 我知道java while循环和if语句,但从未嵌套过它们。 I will first post the script and then tell you guys the problem. 我将首先发布脚本,然后告诉你们这个问题。

here is the script: 这是脚本:

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);
        }
    }
}
}

First of all, i have no knowledge about this type of nesting i am just experimenting right now so maybe that's why my method may seem a bit unusual to you people. 首先,我不知道这种类型的嵌套我现在只是在试验,所以也许这就是为什么我的方法对你们来说似乎有点不寻常。

now, the problem is that whenever i execute this code, the infinite while loop works perfectly but it always skips the if statement no matter what i input and starts to loop the instructions again. 现在,问题是每当我执行这段代码时,无限循环工作完美但它总是跳过if语句,无论我输入什么并开始再次循环指令。

please help me with this. 请帮我解决一下这个。

use 采用

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

equalsIgnoreCase compares contents but == compares references and in you case references would not be same as you are using scan.nextLine(); equalsIgnoreCase比较内容,但==比较引用,在你的情况下,引用与你使用scan.nextLine(); which creates a new String Object. 这会创建一个新的String对象。

When comparing strings, you need to use the .equals() method, so, in your case, you need to change method == "exit" to method.equals("exit") . 比较字符串时,需要使用.equals()方法,因此,在您的情况下,您需要将method == "exit"更改为method.equals("exit") The same applies for the other if statement. 这同样适用于其他if语句。

You can take a look at this Oracle tutorial for more information on String comparison. 您可以查看 Oracle教程,以获取有关字符串比较的更多信息。

If you use == to compare strings this will compare the reference of the object, in which case it will always return false in your case. 如果使用==来比较字符串,这将比较对象的引用,在这种情况下,它将始终返回false。 Since you don't have an else and only an else if you don't actually see this happening and it carries on to the next iteration. 如果您实际上没有看到这种情况,那么您没有其他地方而只有其他地方,并且它会继续进行下一次迭代。

Change it to .equals() method to compare object value rather than reference. 将其更改为.equals()方法以比较对象值而不是引用。

Side Note 边注

Be careful with reference comparison as you may have seen the odd example where reference equality is used which may throw you (it certainly did for me the first time as this example below shows). 请注意参考比较,因为您可能已经看到了使用引用相等性的奇怪示例,这可能会引发您(这对我来说肯定是第一次,如下面的示例所示)。

String a = "Hello";
String b = "Hello";

If you compare a == b in this case it will actually return true, this is because Java caches strings and so they do in this case have the same reference. 如果你在这种情况下比较a == b它实际上会返回true,这是因为Java缓存了字符串,因此在这种情况下它们具有相同的引用。 Be careful when you see examples like this as they are the exception. 当你看到这样的例子时要小心,因为它们是例外。

Use method.equals("exit") for String comparison. 使用method.equals("exit")进行字符串比较。

See this post. 这篇文章。

== Its test reference equality for the objects. ==它对象的测试引用相等。

equals(String) This is a method in String class to comparing the content of two string. 等于(字符串)这是一种方法,String类两个字符串的内容进行比较。

In java, == means checking reference equality , except numbers. 在java中, ==表示检查reference equality ,但数字除外。 (see comments below) (见下面的评论)

Object obj1 = new Object();//toString: java.lang.Object@459189e1 <--|
                                                                  //|- different addresses
Object obj2 = new Object();//toString: java.lang.Object@55f33675 <--|
obj1 == obj2; //false, because they are difference objects, difference references.

obj1 = obj2;
obj1 == obj2; //true, they are now pointing to the same object

So, you need use .equals to check String equality. 因此,您需要使用.equals来检查字符串相等性。

This is a problem with all beginners. 这是所有初学者的问题。 I had done it when I started. 我开始的时候就做过了。 The problem here is 这里的问题是

the equality operator == 等于运算符==

should not be used to compare two strings here. 这里不应该用来比较两个字符串。 Because it is used to check any two objects are no different but of a same instance. 因为它用于检查任何两个对象没有区别但是同一个实例。 ie

Object O1 = new Object()
Object o2 = o1

Here 这里

o1 == o2 o1 == o2

will evaluate to true. 将评估为真。 Because they check for the referential equality. 因为他们检查参照平等。

In the case of string, when you are comparing the content of the strings, you should always compare themeither with 在string的情况下,当您比较字符串的内容时,您应该始终将theme与之比较

equals 等于

method or 方法或

equalsIgnoreCase equalsIgnoreCase

if you are not bothered about the case. 如果你不为这个案子烦恼。 God bless. 上帝保佑。 Cheers. 干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM