+ 2
Computer fails to recognize my input
package programlearning; import java.util.Scanner; public class Passwordtest { private static Scanner Password; public static void main(String[] args) { System.out.println("Input Password Please"); Password = new Scanner(System.in); String x= Password.nextLine(); if(x== "lolz"){ System.out.println("Password is Correct"); } else{ System.out.println("Wrong"); } } } I tried to make a password program, but whenever I input lolz it says that its wrong?
10 Respostas
+ 8
This will work.
if(x.equals("lolz")){
System.out.println("Password is Correct");
}
+ 2
why if(x=="lolz") will not work because u r comparing string content not the string references.when we want to compare atring content, we use equals or equalsIgnoreCase mwthod
+ 1
pls try with if(x.equals("lolz")) instead of if(x== "lolz")
+ 1
It worked, thank you so much!
+ 1
answer to the question of mehdi-whenever we assign a value to a string without using new keyword...it first checks the value in string pool..if found it assigns the reference of that object..else creates a new object...so above when you are assigning the lolz string literal to y..same thing happens here and a new string object is being created..and scanner also creates a new object in heap.so references are not same...that why else part is getting executed all the time.
0
why if(x=="lolz") not work?
what's the problem?
0
so why this one not work
string y="lolz";
if(x==y)
x and y both are string
0
might be the case, when we use Scanner object to read input, the string read is stored as new String() object where as in y="lolz" we used as string literal. Though I'm not very sure of thia.
0
import.java.util.scanner
0
first take that correct paswrd and store it in variable and then compare with x which is entered paswrd