在Java中,我有两个while循环来验证用户的输入,如果用户输入了错误的数据类型,就会不断地提示用户。在这个程序中,我只有两个问题,但我可以想象一个场景,在这个情况下,我有超过10个循环,此时读取和维护的代码会很麻烦。是否有更有效的方法来检查错误,同时继续提示用户?我最初的想法是将while循环和错误检查打包到一个单独的类函数中,并在请求输入时调用它。
import java.util.*;
公共类IncreaseAge {
public static void main(String args[]){
Scanner userInput = new Scanner(System.in);
boolean validInput = true;
String coolName = "Adam";
int coolAge = 0;
while(validInput){
try{
System.out.print("Hello, what is your first name? ");
coolName = userInput.nextLine();
validInput = false;
}
catch(Exception error){
System.out.println("Invalid input, try again!");
userInput.next();
}
}
validInput = true;
while(validInput){
try{
System.out.print("Hi "+ coolName + "! How old are you?");
coolAge = userInput.nextInt();
validInput = false;
}
catch(Exception error){
System.out.println("Invalid input, try again!");
userInput.next();
}
}
System.out.println("Hello "+ coolName + ", in ten years you will be " + (coolAge+10));
userInput.close();
}
}
发布于 2021-12-22 11:25:51
只需实现private int getIntegerInput(String prompt)
和private String getStringInput(String prompt)
,每个循环与您已经编码的两个循环大致相同。
这是一种常见且频繁的避免代码重复的方法--实现用于编写预期功能的“助手”例程。
即使您不需要担心重复,这也是一种有用的代码分区,使代码更容易理解--例如,“获取输入”代码显然与“处理输入”代码不同。
示例:
private String getStringInput(Scanner scanner, String prompt) {
String input = null;
boolean validInput = false;
while (!validInput) {
try {
System.out.print(prompt);
input = scanner.nextLine();
validInput = !input.isEmpty();
}
catch (Exception error) {
System.out.println("Invalid input, try again!");
}
}
return input;
}
请注意,我修正了“validInput”的用法,并假定您希望在空的输入行上重新提示。
这样,用法就像
String coolName = getStringInput(userInput, "What is your first name? ");
https://stackoverflow.com/questions/70453114
复制