|
im trying to write an easy program that lets me enter a password and if it's correct it will say access granted.
This is not for homework, it's just something i'm writing for fun to keep my programming knowledge fresh over the summer. im guessing something is not right with the "if" statement here. any help appreciated thanks.
code:
import java.util.Scanner; public class summer { public static void main(String [] args){ Scanner input = new Scanner(System.in); String[] password = new String[1]; System.out.print("You are entering unauthorized territory. Please enter password: "); password[0] = input.nextLine();
if(password[0] == "1234"){ System.out.print("Access Granted"); } } }
|
Dude I was terrible at C++ when I took it in high school so I heard Java is a little harder good luck trying to figure this out
|
Use String.equals, not == when comparing strings.
|
You are comparing a reference to a string with the string "1234" which will always return false. The proper way of making your comparison in this case would be:
if( password[0].equals("1234") )
|
As others have said, == is not right. Only with primitives (i.e. int, char, etc.) does == compare values - with objects, it compares the references (physical addresses) of each object. Either use the .equals(), .compareTo(), or .compare() method to check your string's value.
|
I mean no offence by this, but if this is keeping your knowledge "fresh"... Exactly what do they teach in the span of one year nowadays? :o
Edit: WHOA BOY DID I EVER JUST NECRO. Was using the search feature and not paying attention to dates because I'm an idiot. I may have done this to a few threads...
|
|
|
|