0

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

我究竟做错了什么?

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

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.

4

2 回答 2

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

    }

应该做的伎俩?

于 2015-04-08T19:13:33.467 回答
0

Your guess was right.

    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;
    }

Probably careless mistake. Needs a if(name.contains(" ")):D Same thing happened for your password block.

于 2015-04-08T19:10:51.880 回答