使用do-while循环测试输入是否为Integer且大于(两个条件) - Java [英] Testing if an input is Integer and larger than (two conditions) with do-while loop - Java
本文介绍了使用do-while循环测试输入是否为Integer且大于(两个条件) - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要用户输入为整数且大于10。
I need input from a user to be integer and larger than 10.
这是我的代码。
import java.util.*; //program uses class Scanner
public class Tests {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter an Integer");
int weight;
do {
while (!input.hasNextInt()) {
System.out.println("Please enter an integer!");
input.next(); // this is important!
}
System.out.println("Enter an Integer >= 10");
weight = input.nextInt();
} while (weight < 10);
System.out.println("OK");
}
}
我的预期输出如果重量是整数,则打印OK。
但是我的实际输出是
My expected output will be to if the weight is integer to print "OK". But my actual output is
Enter an Integer
20
Enter an Integer >= 10
OK
我无法弄清楚如何摆脱输入整数条件满足时> = 10。
I cannot figure out how to get rid of the "Enter an Integer >= 10" when conditions satisfied.
推荐答案
如果输入不满足条件,则只打印消息。
Only print the message if the input does not satisfy the condition.
do {
while (!input.hasNextInt()) {
System.out.println("Please enter an integer!");
input.next(); // this is important!
}
weight = input.nextInt();
if ( weight < 10 ) {
System.out.println("Enter an Integer >= 10");
}
} while (weight < 10);
这篇关于使用do-while循环测试输入是否为Integer且大于(两个条件) - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文