我需要创建一个异常类,当用户输入的名称、密码等(所有字符串)中有空格时,它将引发异常。我已经编写了所有我认为必要的代码,无论我输入什么,总是会抛出异常。
我究竟做错了什么?
以下是代码片段。如果需要整个程序,请告诉我。
EmptyInputException
班级:
public class EmptyInputException extends Exception{
public EmptyInputException(){
super("ERROR: Spaces entered - try again.");
}
public EmptyInputException(String npr){
super("ERROR: Spaces entered for " + npr + " - Please try again.");
}
}
这是getInput
我捕获异常的方法:
public void getInput() {
boolean keepGoing = true;
System.out.print("Enter Name: ");
while (keepGoing) {
if(name.equalsIgnoreCase("Admin")){
System.exit(1);
}else
try {
name = scanner.next();
keepGoing = false;
throw new EmptyInputException();
} catch (EmptyInputException e) {
System.out.println("ERROR: Please do not enter spaces.");
keepGoing = true;
}//end loop
}
System.out.print("Enter Room No.:");
while (keepGoing) {
if(room.equalsIgnoreCase("X123")){
System.exit(1);
}else
try {
room = scanner.next();
if (room.contains(" ")){
throw new EmptyInputException();
}else
keepGoing = false;
} catch (EmptyInputException e) {
System.out.println("ERROR: Please do not enter spaces.");
keepGoing = true;
}
}
System.out.print("Enter Password:");
while (keepGoing) {
if(pwd.equals("$maTrix%TwO$")){
System.exit(1);
}else
try {
pwd = scanner.next();
keepGoing = false;
throw new EmptyInputException();
} catch (EmptyInputException e) {
System.out.println("ERROR: Please do not enter spaces.");
keepGoing = true;
}
}
}
我觉得我错过了扫描仪输入应该包含空格的部分,例如:
if(name.contains(" "))
等等...
到目前为止,我的输出(例如,在输入名称之后)会说,Error: Please do not put spaces.