我有一个方法用于验证程序中的用户输入值。每当用户输入一个字符串到一个JOptionPane中时,我会调用这个方法并传入输入的字符串,加上我需要输入的最大值和最小值。首先,我通过尝试解析输入字符串并捕获异常来检查输入是否为整数,然后检查整数是否在最小值和最大值之间。我的问题是,如果用户在提示后输入另一个不正确的非整数值,我不知道如何检查新值是否正确。这是方法,任何人都可以帮忙吗?持续验证整数
int checkInput(String input, int min, int max) {
Boolean isInteger = false;
Boolean inputAccepted = false;
int userInput = 0; //will be set later
while (!isInteger) {
try
{
userInput = Integer.parseInt(input);
}
catch (NumberFormatException e)
{
userInput = Integer.parseInt(JOptionPane.showInputDialog("Please enter only integers between " + min + " and "+ max + "."));
isInteger = true; //the problem here is that it assumes the user inputted a correct value after being prompted... what if they enter another incorrect value?
}
}
while (!inputAccepted) {
if (userInput < min || userInput > max)
{
userInput = Integer.parseInt(JOptionPane.showInputDialog("Please enter only integers between " + min + " and "+ max + "."));
}
else
{
inputAccepted = true;
}
}
return userInput;
}
也许你可以检查用户输入的每个值后? – Lucas
这就是我想要做的,但我不熟悉try和catch语句,所以我不确定如何在第一次进行循环检查时如何做到这一点。 – user3738313