0

I'm trying to check a string for a specific number but it doesn't seem to find it.

string = sc.next();

if(string != "-1")
 return 0;

So when I enter -1 into the input, it just continues on without breaking the program. Am I doing something wrong here?

SatyaTNV
  • 4,137
  • 3
  • 15
  • 31

2 Answers2

2

Instead of != you need to use the operator NOT ! and the method equals

So

string = sc.next();

if (!string.equals("-1")) 
   return 0;

Remember infact that the operators == (or !=) check for same (or not same) object. Instead equals method check that the internal value of the string is the same of the parameter.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
0

If you are expecting a number I would read a number.

int num = sc.nextInt();

if (num != -1) return 0;

BTW: When you use == or != for String it compares only the references, not the contents of the Strings.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130