Java Scanner Class

I am writing a program that should close the console if the user enters the string "end". A program always executes an else loop, even if the user enters "end". I wonder why the program does not fall into the if-part of the loop and closes.

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

  if(num == "end")
  {
   System.exit(0);
  }
  else
  {
   System.out.println("hi");
  }
 }
+3
source share
6 answers

You use ==instead"end".equals(num)

+7
source

Do not use == to equal the 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 enter end or END

"end" .equals(num), , -, .

, num null, , num.quals( "end" ) , if (num!= null && num.equals( "end" ) ) {...}

, "end" .equals(num) , - , , if (num!= null && num.equals( "end" )) {...}

+5

equals().

if(a.equals(b)) ..

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

+2
source

In Java, you check for equality of strings:

string1.equals(string2);

So in this case it will be:

num.equals("end");

Or to avoid a type exception NullPointerException:

"end".equals(num);
+1
source

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

0
source

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

0
source

Source: https://habr.com/ru/post/1762365/


All Articles