[英]Java - How to reprompt the user if the input is not an integer
如果输入的值不是整数,我想重新提示用户。 我是Java新手。 亲切地建议我最好的方式,我可以再次提示(noofcases)用户再次输入整数值,直到用户输入整数值为止。
public static void main(String[] args)
{
fetchinput();
}
public static void fetchinput()
{
int noofcases = 0;
Scanner input= new Scanner(System.in);
noofcases=input.nextInt();
ArrayList<String> StringA = new ArrayList<String>();
ArrayList<String> StringB = new ArrayList<String>();
for (int i=0;i<noofcases;i++)
{
StringA.add(input.next());
StringB.add(input.next());
}
input.close();
System.out.println(StringA);
System.out.println(StringB);
}
尝试在try {} catch(NumberformatException e)中使用Integer.parse()转换输入字符串,并在新输入请求发生异常时将其输出到System out。 剩下的就是再次读取相同的输入流。 如果需要,可以在while循环中进行操作,也可以计算变量中止失败的次数。
这是我倾向于使用的方法:
public int getNextInt(String promptMessage) {
Integer ret; //We use Integer so it can be null
do {
System.out.println(promptMessage);
String str = in.nextLine(); //nextLine is cleaner and doesn't get caught on newline characters
try {
ret = Integer.parseInt(str);
catch(NumberFormatException e) { //Invalid
System.out.println("Input an integer.");
}
} while(ret==null); //Loop while invalid
return ret; //Return result, unboxed
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.