Wednesday 7 August 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...