this is my code :
import java.util.Scanner;
public class OnlineBookStore {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Welcome to my online book store!");
System.out.println(" ");
System.out.println("Which user are you?");
System.out.println("1. Admin");
System.out.println("2. Buyer");
System.out.println("3. Seller");
int option = in.nextInt();
if (option == 1) {
String user, pass;
System.out.println("Enter your username: ");
user = in.nextLine();
System.out.println("Enter the password: ");
pass = in.nextLine();
if(user.equals("Admin1") || (pass.equals("Best"))) {
System.out.println("test");
} else {
System.out.println("Wrong password.");
}
}
}
}
this is the output:
Welcome to my online book store!
Which user are you?
- Admin
- Buyer
- Seller
1
Enter your username:
Enter the password:
Admin1
Wrong password.
>Solution :
What is happening is that you Scanner only read the int but did not clear the rest of the buffer, what you can do is simply make a call to nextLine() and this will fix your problem!
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Welcome to my online book store!");
System.out.println(" ");
System.out.println("Which user are you?");
System.out.println("1. Admin");
System.out.println("2. Buyer");
System.out.println("3. Seller");
int option = in.nextInt();
in.nextLine();
if (option == 1) {
String user, pass;
System.out.println("Enter your username: ");
user = in.nextLine();
System.out.println("Enter the password: ");
pass = in.nextLine();
if(user.equals("Admin1") || (pass.equals("Best"))) {
System.out.println("test");
} else {
System.out.println("Wrong password.");
}
}
}
}