我正在设置一个while()
,直到用户输入一个整数为止。但是,就我现在的方式而言,循环在输入整数后再次打印消息"Please enter an integer"
,然后程序正常执行。有人建议在输入整数后再次打印该消息的方法吗?谢谢!
System.out.println("Enter word length");
if(in.hasNextInt())
{
n = in.nextInt();
}
else
{
while(in.hasNext()) //this is the loop i'm talking about
{
System.out.println("Please enter an integer");
if(in.hasNextInt())
{
n = in.nextInt();
break;
}
else
{
String c = in.next();
}
}
}
答案 0 :(得分:2)
我假设您希望用户输入int(或Integer)并反复询问用户,直到用户输入int(或Integer)。如果是这样,试试这个:
System.out.println("Enter word length");
if(in.hasNextInt()) {
n = in.nextInt();
} else {
while(in.hasNext()) //this is the loop i'm talking about
{
if(in.hasNextInt())
{
n = in.nextInt();
break;
}
else
{
String c = in.next();
System.out.println("Please enter an integer");
}
}
}