Java 异常处理(用户输入中的空格)

Java Exception Handling (Empty spaces in user input)

我需要创建一个异常 class,当用户输入的名称、密码等(所有字符串)中有空格时将引发异常。我已经编写了所有我认为必要的代码,无论我输入什么,总是抛出异常。

我做错了什么?

以下是代码片段。如果需要整个程序,请告诉我。

EmptyInputException class:

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.

你猜对了。

    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 您的密码块也发生了同样的事情。

try {
        name = scanner.next();
        keepGoing = false;
        if(name.contains(" "))
            throw new EmptyInputException();

    }

应该这样做吗?