java.util.scanner - Newbie to Java, wondering about if statements and strings that are read by Scanner -
so, started java
today , playing around scanner
object after having watched tutorial on how guy used find area of triangle. maybe i'm doing wrong, but, decided mess , see if incorporate "if" statement it.
import java.util.scanner; public class test { static scanner sc = new scanner(system.in); /* * in = input keyboard or other device. * system class. */ public static void main(string[] args){ { string password; //this our variable - password system.out.print("enter password:"); password = sc.next(); //we have gotten user input words, work on displaying final message //using if if (password.equals(one)) system.out.println("you have logged in successfully"); } } }
that's code , apologize if looks shoddy - still trying learn.
my issue is, want if statement go through if input specific password ("one"). however, error because says value 'one' cannot resolved variable. when input numbers, works fine.
what doing wrong , how can fix it?
first off, class capitalized public class test
should public class test
.
you need compare explicitely string. one
defined nowhere, code not work.
replace:
if (password.equals(one))
with
if (password.equals("one"))
and go.
instead, declare password in header of class :
string pw = "one";
and check
if (password.equals(pw))
but remember never safe treat passwords way, in any programming language. password should hashed , stored in database. still learning, consider second method (declaring string want compare to) 'cleaner' way go.
edit - how code work simple variable declaration
import java.util.scanner; public class test { string pw = "one"; string pw2; /* constructor class can override existing variables or set variable declared in header of class inside constructor of class. run whenever create new object class */ public test(string pw2param) { this.pw2 = pw2param; } public static void main(string[] args){ { scanner sc = new scanner(system.in); // instantiate object hold information need test obj = new test("two"); system.out.println(obj.pw); // "one" system.out.println(obj.pw2); // "two" system.out.println("enter password:"); string password = sc.next(); if (password.equals(obj.pw)) { system.out.println("you have typed 'one' , logged in successfully"); } else if(password.equals(obj.pw2)) { system.out.println("you have typed 'two' , logged in successfully"); } else { system.out.println("i didn't that"); } } } }
i hope makes sense :)
i beginner, found habit compile java code using javac
in console. ruthless in comparison ide i've used , point @ general errors ide might forgive/correct you.
Comments
Post a Comment