我需要创建一个异常类,当用户输入中有空格用于名称,密码等(所有字符串)时,将抛出异常。我已经编写了我认为必要的所有代码,无论我输入什么,都会抛出异常。
我做错了什么?
以下是代码片段。如果需要整个程序,请告诉我。
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.
答案 0 :(得分:1)
try {
name = scanner.next();
keepGoing = false;
if(name.contains(" "))
throw new EmptyInputException();
}
应该这样做吗?
答案 1 :(得分:0)
你的猜测是正确的。
try {
name = scanner.next();
keepGoing = false;
throw new EmptyInputException(); // You're always going to throw an Exception here.
} catch (EmptyInputException e) {
System.out.println("ERROR: Please do not enter spaces.");
keepGoing = true;
}
可能是粗心的错误。需要if(name.contains(" "))
:D密码块也发生了同样的事情。