Java Try/Catch异常未按计划工作

Java Try/Catch异常未按计划工作,java,exception,try-catch,helper,Java,Exception,Try Catch,Helper,我被这个难住了——我为一个helper方法编写了一个try/catch。它的目的是捕获任何无效的输入(任何不是“男性”或“女性”的输入(无特定情况)。如果输入无效,它将通知用户,然后让用户重试。如果输入有效,该方法将返回输入 当我运行程序时,它不会捕获无效的输入。为什么这不起作用 以下是帮助器方法: //Helper method that gathers the string input from user public static String getString() { //C

我被这个难住了——我为一个helper方法编写了一个try/catch。它的目的是捕获任何无效的输入(任何不是“男性”或“女性”的输入(无特定情况)。如果输入无效,它将通知用户,然后让用户重试。如果输入有效,该方法将返回输入

当我运行程序时,它不会捕获无效的输入。为什么这不起作用

以下是帮助器方法:

//Helper method that gathers the string input from user
public static String getString() {

    //Create new scanner input
    Scanner input = new Scanner(System.in);

    //Declare and initialize variables
    String wordIn = "";
    boolean validIn;

    //do/while loop for obtaining input and checking validity (try/catch)
    do {
        validIn = true;
        try{
            wordIn = input.nextLine();

        //End Try   
        }

        catch(Exception invalidInput) {
            validIn = false;
            input = new Scanner(System.in);
            System.out.print("\nYou have entered an invalid input. Please "
                    + "enter either \"Male\" or \"Female\" ONLY for this "
                    + "selection. The selection is not case sensitive."
                    + "\n\nPlease enter your selection: ");

        //End Catch    
        }

    //While input is valid, return the input    
    } while (!validIn);
     return wordIn;

//End helper
}
以下是测试代码:

//Obtain user input and print output
String passGender = getString();
System.out.println("\n" + titanic.getSurvivedPassengersGender(passGender)
                        + " " + passGender.toLowerCase() + " passengers survived the "
                        + "sinking of the Titanic.");

似乎我没有一个正确的条件集……我找不到哪里出了问题。我还是个新手,所以我确信这是一个简单的错误。非常感谢任何帮助。谢谢大家!

你们没有为你们想要的设置任何条件。 您没有设置任何条件来引发非“男性”或“女性”输入的事件。您的代码应该是:

//Helper method that gathers the string input from user
public static String getString() {

//Create new scanner input
Scanner input = new Scanner(System.in);

//Declare and initialize variables
String wordIn = "";
boolean validIn;

//do/while loop for obtaining input and checking validity (try/catch)
do {
    validIn = true;
    try{
        wordIn = input.nextLine();
        if(!(wordIn.equalsIgnoreCase("male") || wordIn.equalsIgnoreCase("female")))
            throw new Exception();
    //End Try   
    }

    catch(Exception invalidInput) {
        validIn = false;
        input = new Scanner(System.in);
        System.out.print("\nYou have entered an invalid input. Please "
                + "enter either \"Male\" or \"Female\" ONLY for this "
                + "selection. The selection is not case sensitive."
                + "\n\nPlease enter your selection: ");

    //End Catch    
    }

//While input is valid, return the input    
} while (!validIn);
 return wordIn;
//End helper
}
编辑此外,正如@ashutosh所说,您不必抛出异常,您只需使用一个条件:

wordIn = input.nextLine();
if(!(wordIn.equalsIgnoreCase("male") || wordIn.equalsIgnoreCase("female"))
     System.out.print("\nYou have entered an invalid input. Please "
                + "enter either \"Male\" or \"Female\" ONLY for this "
                + "selection. The selection is not case sensitive."
                + "\n\nPlease enter your selection: ");

你没有为你想要的东西设定任何条件。 您没有设置任何条件来引发非“男性”或“女性”输入的事件。您的代码应该是:

//Helper method that gathers the string input from user
public static String getString() {

//Create new scanner input
Scanner input = new Scanner(System.in);

//Declare and initialize variables
String wordIn = "";
boolean validIn;

//do/while loop for obtaining input and checking validity (try/catch)
do {
    validIn = true;
    try{
        wordIn = input.nextLine();
        if(!(wordIn.equalsIgnoreCase("male") || wordIn.equalsIgnoreCase("female")))
            throw new Exception();
    //End Try   
    }

    catch(Exception invalidInput) {
        validIn = false;
        input = new Scanner(System.in);
        System.out.print("\nYou have entered an invalid input. Please "
                + "enter either \"Male\" or \"Female\" ONLY for this "
                + "selection. The selection is not case sensitive."
                + "\n\nPlease enter your selection: ");

    //End Catch    
    }

//While input is valid, return the input    
} while (!validIn);
 return wordIn;
//End helper
}
编辑此外,正如@ashutosh所说,您不必抛出异常,您只需使用一个条件:

wordIn = input.nextLine();
if(!(wordIn.equalsIgnoreCase("male") || wordIn.equalsIgnoreCase("female"))
     System.out.print("\nYou have entered an invalid input. Please "
                + "enter either \"Male\" or \"Female\" ONLY for this "
                + "selection. The selection is not case sensitive."
                + "\n\nPlease enter your selection: ");
或者(正如许多人在评论中所说的那样)你应该更好地使用条件,比如:

wordIn = input.next(); 

while(!(wordIn.toLowerCase().equals("male") || wordIn.toLowerCase().equals("female"))){

System.out.println("\nYou have entered an invalid input. Please "
                + "enter either \"Male\" or \"Female\" ONLY for this "
                + "selection. The selection is not case sensitive."
                + "\n\nPlease enter your selection: ");
wordIn = input.next();

}
这将保持循环,直到输入有效字符串,而不需要try-catch。

或者(正如许多评论中所说的),您最好使用条件。例如:

wordIn = input.next(); 

while(!(wordIn.toLowerCase().equals("male") || wordIn.toLowerCase().equals("female"))){

System.out.println("\nYou have entered an invalid input. Please "
                + "enter either \"Male\" or \"Female\" ONLY for this "
                + "selection. The selection is not case sensitive."
                + "\n\nPlease enter your selection: ");
wordIn = input.next();

}

这将保持循环,直到输入有效字符串而不需要try-catch。

After
wordIn=input.nextLine();
,您需要检查它的值。如果它是无效值,那么您需要抛出一个异常,该异常将被catch子句捕获。顺便说一句,为什么您要抛出一个异常,而只需要有一个条件。如果输入字符串不是“男性”或“女性”,然后你可以执行你当前在
catch
clauseYep中的代码-我现在是一个被认证的白痴…这是漫长的一天。我不敢相信我错过了一个事实,我没有为有效的设置条件。多好的一天!抱歉浪费了你的时间,谢谢大家!在
wordIn=input.nextLine()之后;
,您需要检查它的值。如果它是无效值,那么您需要抛出一个异常,该异常将被catch子句捕获。顺便说一句,为什么您要抛出一个异常,而只需要有一个条件。如果输入字符串不是“男性”或“女性”,然后你可以执行你目前在《捕获》条款中的代码-我现在是一个合格的白痴…这是漫长的一天。我不敢相信我错过了我没有为有效的设置条件的事实。真是一天!抱歉浪费了你的时间,谢谢大家!如果(!(wordIn.equalsIgnoreCase(“男性”)| wordIn.equalsIgnoreCase(“女性”)))因为字符串相等不适用于=或!=不知道我到底是怎么错过的-除了我在烟雾中跑步这一事实。我现在感觉自己像个白痴。非常感谢你让我浪费你的时间!我们所有人都遇到了:)@Shobit字符串相等适用于==和!=。只是它的工作原理不同于if(!(wordIn.equalsIgnoreCase(“男性”)| | wordIn.equalsIgnoreCase(“女性”))中描述的
equals()
),因为字符串相等不适用于=或=我不知道我到底是怎么错过的——除了我在烟雾中跑步这一事实。我现在觉得自己像个白痴。非常感谢你让我浪费你的时间!我们每个人都会遇到这样的情况:)@Shobit字符串相等确实适用于==和!=。只是它的工作原理不同于中所述的
equals()
,我理解并同意。我使用try/catch的唯一原因是为了锻炼我在整个课程中学到的东西。我只是想保持它的简单性,不使用try/catch,但是需要包含更多的异常以显示完全的理解。谢谢你的反馈。我理解,也同意。我使用try/catch的唯一原因是为了锻炼我在整个课程中学到的东西。我只是想保持它的简单性,不使用try/catch,但是需要包含更多的异常以显示完全的理解。谢谢你的反馈。