我的问题是,当用户输入字母以外的任何内容时,我需要引发异常。
我无法改变我正在使用 BufferedReader 的事实,因为它是学校作业的一部分。这是我的代码:
public static String phoneList(String lastNameInput, String nameInput)
throws IOException {
BufferedReader bufferedreader = new BufferedReader(
new InputStreamReader(System.in));
try {
System.out.println("Please input your first name.");
// User input block
String input = bufferedreader.readLine();
nameInput = input;
} catch (IOException e) {
System.out.println("Sorry, please input just your first name.");
}
try {
System.out.println("Please input your last name.");
String input2 = bufferedreader.readLine();
lastNameInput = input2;
} catch (IOException e) {
System.out
.println("Sorry, please only use letters for your last name.");
}
return (lastNameInput + ", " + nameInput);
}
那么如果用户输入包含数字或非字母字符,我可以使用什么方法引发异常?
最佳答案
My problem is that I need to throw an exception when the user inputs anything other than string (i.e, an int, float, or double.)
你问的没有意义。为了说明这一点,“12345”是一个字符串。是的。因此,如果您调用 readLine()
并且该行仅由数字组成,您将得到一个仅由数字组成的字符串。
因此,为了解决您的问题,在读取字符串后,您需要验证它以确保它是可接受的“名字”。您可以通过多种方式做到这一点:
- 最原始的方法是迭代字符串,检查每个字符是否可接受。
- 一种稍微不那么粗暴(但可能是错误)的方法可能是尝试将字符串解析为 float 的整数。 (作为练习,弄清楚为什么我说“可能是错的”。)
- 优雅的方法是使用
java.util.regex.Pattern
和匹配可接受名称的模式,并排除不需要的内容,例如数字、嵌入的空格和标点符号。
正如 @DanielFischer 的评论所指出的,您需要仔细考虑名称中应该接受哪些字符。重音符号就是一个例子,其他的可能是西里尔字母或汉字……或连字符。
关于java - 如果用户输入不是字符串,如何引发异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13224624/