我正在编写一个程序,该程序接受用户输入的整数和字符串并对该字符串执行操作。我已经创建了该程序,并且运行良好,我的问题是我现在正在尝试处理某人为userInput输入非整数值的错误,但我不确定该怎么做。我曾尝试使用Try Catch语句,但是这样做时,我不断收到有关userInput变量的错误消息。
我想做的是,当userInput为非整数时,将布尔输入错误设置为true ,以便我的while循环反复询问用户输入一个整数直到他们输入。
public class Q3 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
boolean inputError = false;
try{
System.out.print("Please enter a number between 5 and 10, inclusively: ");
String userInput1 = in.nextLine();
int userInput = Integer.parseInt(userInput1);
}
catch(InputMismatchException e)
{
inputError = true;
}
// If userInput is not between 5 and 10, set the boolean inputError to true.
if (userInput < 5 || userInput > 10)
{
inputError = true;
}
// Repeatedly ask for user input if they do not enter a number between 5 and 10.
while(inputError)
{
System.out.print("Error. Please enter a number between 5 and 10, inclusively: ");
userInput = in.nextInt();
in.nextLine();
if (userInput >= 5 || userInput <= 10)
{
inputError = false;
}
}
// Take user's input for the string.
System.out.print("Please enter a string of length 6 characters: ");
String textToChange = in.nextLine();
int length = 6;
String printArray = "";
String wordsOdd = "";
String finalConcat ="";
String transitionString="";
// Print error if text is not 6 characters long.
while(textToChange.length() != 6)
{
System.out.println("Error! Enter a string of length 6.");
textToChange = in.nextLine();
}
答案 0 :(得分:2)
问题在于变量“ userInput”在try-catch
块内声明,这意味着在该块结束之后将不存在。您应该做的是在main方法开始时对其进行初始化,以便可以从main方法内的任何代码块中全局访问它们
int userInput = 1; // Set default initialisation.
String userInput1 = "";
try {
NumberFormat.getInstance().parse(userInput1);
userInput = Integer.parseInt(userInput1);
}
catch(ParseException e) {
inputError = true; //not a number
}
答案 1 :(得分:0)
您需要检查循环内输入有效性的所有代码:
Scanner in = new Scanner(System.in);
boolean inputError = true;
int userInput = 0;
while (inputError) {
try {
System.out.print("Please enter a number between 5 and 10, inclusively: ");
String userInput1 = in.nextLine();
userInput = Integer.parseInt(userInput1);
inputError = (userInput < 5 || userInput > 10);
} catch (NumberFormatException e) {
inputError = true;
}
if (inputError)
System.out.println("Wrong input");
}
System.out.print("Please enter a string of length 6 characters: ");
..................................
在将有效整数作为userInput
传递之前,以上循环将永远不会结束。