有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

我做错了什么

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

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.


共 (2) 个答案

  1. # 1 楼答案

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

    你应该这么做吗

  2. # 2 楼答案

    你猜对了

        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同样的事情发生在你的密码块上