[ 3 / biz / cgl / ck / diy / fa / ic / jp / lit / sci / vr / vt ] [ index / top / reports ] [ become a patron ] [ status ]
2023-11: Warosu is now out of extended maintenance.

/sci/ - Science & Math


View post   

File: 218 KB, 1366x768, javacode.png [View same] [iqdb] [saucenao] [google]
5861825 No.5861825 [Reply] [Original]

Hello.
I'm learning to program in java and I understand the concepts fairly well. However I seem to be having an issue with my if/else statement. For some reason my simple password checking program outputs that "the password was incorrect" everytime regardless if I entered the correct password or not. Can anyone point out or guide me in the right direction? Thanks

>> No.5861830

In java, everything (excluding base types such as int,float...) is a reference.

Therefore, when you say:
password == "patrick"
You are comparing both variables by reference (which will always be false).

To compare strings, use password.equals("patrick").

>> No.5861844
File: 210 KB, 1024x768, Jshit.jpg [View same] [iqdb] [saucenao] [google]
5861844

>>5861825
>java

gtfo: >>>/prog/

>> No.5861861

Strings aren't a primitive, so when you do if((String)patrick=="patrick"){return true} or whatever, the interpreter sees if("@232fdsfe"=="patrick"), because it interprets what you're saying literally. It doesn't say, "well, that's a string, and we're comparing to a string, so the user must be looking to see if the words are the same", it says, "Well this string is represented as a location in memory, and is being compared to a string. Is the string I'm looking at the same location in memory? No? Well, they're not the same!"

Use if password.equals("patrick") in the condition.

>> No.5861930

just replace that entire if check with this
out.println(password.equalsIgnoreCase("patrick") ? "password correct" : "password incorrect");