开发者

Java Scanner Class [duplicate]

This question already has answers here: How do I compare strings in Java? (23 answers) Closed 4 years ago.

I am writing a program that should close the console if the user input the String "end'. The program always performs the else loop even if the user inputs "end". I'm wondering why the program is not getting into the if part of the loop and shutting down.

Scanner scan = new Scanner(System.in);
 while(true)
 {
  String num = scan.nextLine();

  if(num == "end")
  {
   System.exit开发者_JAVA百科(0);
  }
  else
  {
   System.out.println("hi");
  }
 }


You're using == instead of "end".equals(num)


Don't use == for equality of string as it compares the objects not the string itself.

Use num.equals("end") or num.equalsIgnoreCase("end") if you want to be able to type end or END

I would not use "end".equals(num), although considered better from a performance perspective in most cases, it does not clearly state the business requirement and it is more important to make it more readable.

But be aware of num being null, if that is possible, num.quals("end") could throw an exception and you should write if (num!=null && num.equals("end")) { ... }

Note that "end".equals(num) does not need the null check, but I still believe this is not very readable, so I would go with if (num!=null && num.equals("end")) { ... }


For testing equality between strings, you should use equals() instead.

if(a.equals(b)) and so on.

This should help you out: http://leepoint.net/notes-java/data/expressions/22compareobjects.html


In Java, you test equality of strings with:

string1.equals(string2);

So in this case, it would be:

num.equals("end");

Or to avoid an exception of type NullPointerException:

"end".equals(num);


num refers to the object, so num == "end" should never be. You want num.equals("end")


Please do not use comparison (==) operator when comparing objects in Java. Use equals(Object) instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜