gpt4 book ai didi

java - 尝试/捕获异常未按计划工作

转载 作者:行者123 更新时间:2023-12-01 18:09:55 27 4
gpt4 key购买 nike

我对此感到困惑 - 我为辅助方法编写了一个 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: ");

关于java - 尝试/捕获异常未按计划工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33793524/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com