这是一个测试程序,供用户在员工和经理之间进行选择。如果用户选择员工,它将指导用户登录,经理也是如此。但是,当我错误地输入第一个选择时,当循环指示我输入另一个输入时,我正确输入输入,程序将跳过switch语句(它指示我登录)。为什么?
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int select = 0;
ArrayList<Manager> manager = new ArrayList<Manager>();
ArrayList<Staff> staff = new ArrayList<Staff>();
staff.add(new Staff("LOL","LOL","Slol","asdasd"));
manager.add(new Manager("Jason","Hew","Msdasd","asdasd"));
do {
try {
select = Menu();
switch(select) {
case 1:
SLogIN(staff);
break;
case 2:
MLogIN(manager);
break;
default:
select = Menu();
}
}catch (InputMismatchException e) {
System.out.println("Invalid Selection.");
System.out.println("Please choose only from the options above");
}
}while(select < 1 || select > 2);
}
public static int Menu() {
Scanner scan = new Scanner(System.in);
int input = 0;
System.out.printf("Who are you? \n");
System.out.printf("1. Staff\n");
System.out.printf("2. Manager\n");
System.out.printf("Your Answer : ");
try{
input = scan.nextInt();
}catch (Exception e){
System.out.println("Invalid Selection.");
System.out.println("Please choose only from the options above.");
}
return input;
}
public static boolean MLogIN(ArrayList<Manager> a) {
boolean valid = true;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Manager ID :");
String id = scan.next();
System.out.print("Enter Password :");
String pass = scan.next();
if(id.startsWith("M")) {
valid = true;
for(int i = 0; i < a.size(); i++) {
if(id.equals(a.get(i).getID())) {
valid = true;
if(pass.equals(a.get(i).getPass())) {
valid = true;
}
else {
valid = false;
System.out.println("Invalid Username or Password.");
}
}
else {
System.out.println("Invalid Username or Password.");
valid = false;
}
}
}
else {
valid = false;
System.out.println("Invalid Username or Password.");
}
return valid;
}
public static boolean SLogIN(ArrayList<Staff> a) {
boolean valid = true;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Staff ID :");
String id = scan.next();
System.out.print("Enter Password :");
String pass = scan.next();
if(id.startsWith("S")) {
valid = true;
for(int i = 0; i < a.size(); i++) {
if(id.equals(a.get(i).getID())) {
valid = true;
if(pass.equals(a.get(i).getPass())) {
valid = true;
}
else {
valid = false;
System.out.println("Invalid Username of Password.");
}
}
else {
System.out.println("Invalid Username or Password.");
valid = false;
}
}
}
else {
valid = false;
System.out.println("Invalid Username or Password.");
}
return valid;
}
}
答案 0 :(得分:0)
删除default
块。在select = Menu();
之后,您已经在do-while
循环的顶部放置了try
。
do {
try {
select = Menu(); // <-- this is at the top.
switch (select) {
case 1:
SLogIN(staff);
break;
case 2:
MLogIN(manager);
break;
// default:
// select = Menu();
}
} catch (InputMismatchException e) {
System.out.println("Invalid Selection.");
System.out.println("Please choose only from the options above");
}
} while (select < 1 || select > 2);