java - Why does the scanner gets te wrong input? -


this question has answer here:

the input word. if word hello should print: hello sir etc if input not hello should print: why dont hello? problem prints: why dont hello? why this?

scanner input =new scanner(system.in); string word=input.nextline(); if(word=="hello"){     system.out.println("hello sir have day"); } else{     system.out.println("why dont hello?"); } 

you have use method equals() instead of comparing 2 strings operator ==

the == operator check identity of 2 operands.

in case new string created when call method nextline on scanner. calling operator == results in false results, instead calling equals check internal content of both strings returns true.


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -