JAVA: does anyone know why this doesn't work? System.out.println("enter a"); Scanner sc2 = new Scanner(System.in); String continueInput = new String(); continueInput = sc2.nextLine(); if (continueInput == "a"){ System.out.println("good"); } else { System.out.println("bad"); }
What is the code supposed to do: if you type 'a', it will print good; or else, it will print 'bad' but apparently, even i type 'a', it still prints 'bad'.. can anyone tell me why please?
not too sure, I know that == "" is discouraged. I would see if you can do continuedInput.equals("a");
What is the value of continueInput that makes the program print "bad"? That will help you resolve the issue.
he said that no matter what it prints bad. Even if not, that doesn't solve our case of why it's not good.
Is the scanner stripping invisible characters? Say a newline?
@KonradZuse Yes, he did say that---but he never tells us the ACTUAL value of the variable. He only shares what he inputs in the variable. Chances are the variable is not taking his input properly...which is why I asked the actual variable value.
obviously he is going to enter a..... This code works. public class JavaApplication12 { public JavaApplication12() { System.out.println("enter a"); Scanner sc2 = new Scanner(System.in); String continueInput = new String(); continueInput = sc2.nextLine(); if (continueInput.equals("a")) { System.out.println("good"); } else { System.out.println("bad"); } } public static void main(String[] args) { new JavaApplication12(); } }
again == is discouraged and .equals is preferred. .equals is based on an object. I have tested this out and it works. For some reason my system print statements were backwards.... i.e., bad then good not good then bad.
also 'a' and 'A' are NOT the same.
Join our real-time social learning platform and learn together with your friends!