Java if else not working -


this question has answer here:

i have simple code in java returns "game over.".

import java.util.scanner; public class nextquestion {     public void newquestion() {         scanner choice2 = new scanner(system.in);         system.out.println("what name?");         system.out.println("a. mark");         system.out.println("b. robert");         system.out.println("c. mio");         system.out.println("d. samantha");         string answer2 = choice2.nextline();         if(answer2 == "a" || answer2 == "a") {             system.out.println("game over.");             system.exit(0);         } else if(answer2 == "b" || answer2 == "b") {             system.out.println("nice guess!");             system.exit(0);         } else if(answer2 == "c" || answer2 == "c") {             system.out.println("game over.");             system.exit(0);         } else if(answer2 == "d" || answer2 == "d") {             system.out.println("game over.");             system.exit(0);         } else {             system.out.println("game over.");             system.exit(0);         }     } } 

however if use switch statement, work. problem this?

do not use "==" compare string not viable, should use if answer2.equals("a") == tests reference equality. .equals() tests value equality. consequently, if want test whether 2 strings have same value should use .equals(). there few situations can guarantee 2 strings same value represented same object because of string interning. cases specified java language specification. == testing whether 2 strings same object


Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

php - Find a regex to take part of Email -