Wednesday, August 7, 2019

Java conditional statement






Possible Duplicate:
Java String.equals versus ==






I am using jcreator to practice java language. I came up with a conditional statement in which if the user input is = "test" it will print an "okay!" message. This is my code:



class conditional {


public static void main (String[] args) {

Scanner user_input = new Scanner(System.in);

String username;
System.out.print("username: ");
username = user_input.next();
if (username == "test") {
System.out.println("okay");
}

else {
System.out.println("not okay");
}
}


The above code does not show any error, it does not display the "okay" && "not okay" message either. I am not sure what's wrong with my logic.


Answer



as @veer said,
you can use equalsIgnoreCase / equals

if (username.equals("test")) { ... }




Or



You can use compareToIgnoreCase / compareTo



if (username.compareTo("test")==0) { ... }

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...