Reputation: 9
package Tutorial;
import java.util.Scanner;
public class Tutorial {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String name="revolt";
int password=0123;
String Name;
int Password;
System.out.println("enter name;");
Name=sc.nextLine();
if (Name.equals(name)){
System.out.println("enter password");
}
else{
System.out.println("wrong Name");
}
Password=sc.nextInt();
if (password==Password){
System.out.println("access granted...");
}
else{
System.out.println("wrong
Password!");
}
}
}
The code doesn't show any error but when I enter password it tells me wrong password even though the password is correct.
Upvotes: 0
Views: 93
Reputation: 9192
You now know what the issue is but, if you are determined to force a User to provide a numerical password (regardless of the order of digits) then make password a String variable and utilize the Scanner#nextLine() method to get User input. Once you have that input, check it using the String#matches() method with a small Regular Expression (regex) to ensure that only numerical digits were supplied, for example:
/* User must enter an all numerical password that is a
minimum of 4 digits to a maximum of 18 digits. */
String password = "";
while(password.isEmpty()) {
System.out.println();
System.out.println("Enter your numerical Password: --> ");
System.out.print ("(enter 'q' to quit): --> ");
password = sc.nextLine().trim();
if (password.equalsIgnoreCase("Q")) {
System.out.println("Quitting ... Bye-Bye");
System.exit(0);
}
// Password must be all numerical,
// be a minimum of 4 digits in length,
// and be a maximum of 18 digits in length.
if (!password.matches("\\d+") || password.length() < 4 || password.length() > 18) {
System.err.println("Invalid Password Supplied (" + password + ")!\n"
+ "A password must contain a 'minimum' of at least four (4)\n"
+ "all numerical digits to a 'maximum' of 18 digits! No alpha\n"
+ "characters or whitespaces are allowed!");
password = "";
}
}
The Regular Expression \\d+
within the String#matches() method checks to make sure that what is now within the password string variable is indeed a string representation of one or more numerical digits from 0 to 9. A password of 0123
would be considered valid however if you were to parse this to Integer or Long for example, the 0
is omitted.
Upvotes: 1