处理输入非整数变量Java的错误
我正在编写一个程序,它接受用户输入的整数和字符串,并对字符串执行操作。我已经创建了这个程序,它运行得很好,我的问题是,我现在正在尝试处理有人为userInput输入非整数值的错误,我不知道该怎么做。我曾尝试使用Try-Catch语句,但在这样做时,我不断收到userInput变量的错误消息
我想做的是当userInput不是整数时,将布尔inputError设置为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();
}
# 1 楼答案
您需要检查循环内输入有效性的所有代码:
在将有效整数作为
userInput
传递之前,上述循环永远不会结束# 2 楼答案
问题是变量“userInput”是在
try-catch
块内声明的,这意味着在该块结束后将不存在。您应该做的是在主方法开始时初始化它们,以便可以从主方法内的任何代码块全局访问它们