+ 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?

27th Aug 2016, 6:11 PM
Adam Lang
Adam Lang - avatar
10 Respostas
+ 8
This will work. if(x.equals("lolz")){ System.out.println("Password is Correct"); }
27th Aug 2016, 6:27 PM
Mahender
Mahender - avatar
+ 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
27th Aug 2016, 6:33 PM
Mahender
Mahender - avatar
+ 1
pls try with if(x.equals("lolz")) instead of if(x== "lolz")
27th Aug 2016, 6:24 PM
Mahender
Mahender - avatar
+ 1
It worked, thank you so much!
27th Aug 2016, 6:28 PM
Adam Lang
Adam Lang - avatar
+ 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.
30th Aug 2016, 8:16 AM
Rahul
Rahul - avatar
0
why if(x=="lolz") not work? what's the problem?
27th Aug 2016, 6:30 PM
mehdi
0
so why this one not work string y="lolz"; if(x==y) x and y both are string
27th Aug 2016, 6:40 PM
mehdi
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.
27th Aug 2016, 6:53 PM
Mahender
Mahender - avatar
0
import.java.util.scanner
13th Sep 2016, 5:26 PM
Dhruv dwivedy
Dhruv dwivedy - avatar
0
first take that correct paswrd and store it in variable and then compare with x which is entered paswrd
15th Sep 2016, 1:06 PM
Altamash Bagwan
Altamash  Bagwan - avatar