What is wrong with my code???
I have problem with my if statement. Even I input user still it is going to else statement. Can some explain to whats is the problem with my code... Thanks...
Code Java:
import java.util.Scanner;
class Login {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String user, pass;
System.out.println("Enter your Username: ");
user = input.nextLine();
System.out.println("Enter your Password: ");
pass = input.nextLine();
if (user == "user" && pass == "admin")
System.out.println("Access granted!!!");
else
System.out.println("Access denied!!!");
}
}
Re: What is wrong with my code???
Re: What is wrong with my code???
Welcome to JAVA 101! We must get this question like 5 times a day on this forum.
Basically, Strings (which is what user and pass are) should be compared using one of the String comparing methods. Specifically, if you want to check two Strings for the same value (case-sensitive), use the String.equals(String) method. If you want to check two Strings for the same value (not case-sensitive), use the String.equalsIgnoreCase(String) method.
The use of the == sign is telling the program to check the two Strings to see if they share the same spot in memory, not to compare their values.
Similarly, to compare any objects for the same value, you should use the Object.equals(Object) method, not the == sign.
The only case where you should use the == sign to check value is with simple-type numbers (such as ints, double, floats, ect.).
Re: What is wrong with my code???
Thanks aussiemcgr...
Code java:
import java.util.Scanner;
class Login {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String user, pass;
System.out.println("Enter your Username: ");
user = input.nextLine();
System.out.println("Enter your Password: ");
pass = input.nextLine();
if (user.equals("user") == true && pass.equals("pass") == true)
System.out.println("Access granted!!!");
else
System.out.println("Access denied!!!");
}
}
Re: What is wrong with my code???
You don't need to have:
if (user.equals("user") == true && pass.equals("pass") == true)
This will do:
if (user.equals("user") && pass.equals("pass"))