【发布时间】:2014-06-13 16:03:08
【问题描述】:
我有一个方法用来验证程序中用户输入的值。每当用户将字符串输入到 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;
}
【问题讨论】:
-
也许您可以在用户输入每个值后进行检查?
-
这就是我想要做的,但我不熟悉 try 和 catch 语句,所以我不确定如何在第一次进行循环检查的同时做到这一点。跨度>
标签: java swing validation