我试图从用户输入的列表中找到最小的数字。我需要询问用户列表中将包含多少个数字(并且只接受正数且不接受字母),然后询问他们列表中的数字是多少(仅接受数字)。我如何检查这一点并继续循环直到数字有效?
public class SmallestInt {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Initialize a Scanner to read input from the command line
Scanner input = new Scanner(System. in );
int totalIntegers = 1;
int num = 0;
int smallest = 0;
boolean inputValid = false;
/* Prompt the user and validate their input to ensure they've entered a positive (greater than zero) integer. Discard/ignore any other data.
*/
while (!inputValid)
{
System.out.print("How many integers shall we compare? (Enter a positive integer): ");
try {
totalIntegers = input.nextInt();
inputValid = true;
} catch (NumberFormatException e) {
System.out.println("Invalid input!");
}
/* Read in the candidates for smallest integer
* Validate this input as well, this time ensuring that the user has provided a valid int (any int will do at this point) and discarding any other data
*/
for (int ii = 1; ii <= totalIntegers; ii++) {
// Prompt
System.out.print("Enter value " + ii + ": ");
num = input.nextInt();
if (ii == 1) smallest = num;
else if (num < smallest) smallest = num;
}
// display smallest int
System.out.println("The smallest number entered was: " + smallest);
}
}
}
最佳答案
让我们为您提供示例,以便您可以按照蓝图
首先,我选择了do while loop,因为你至少需要问一次这个问题。
do...while 循环 的语法是:
do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false.
接下来,您需要了解如何在输入正确时稳定 boolean_experssion,以便停止循环,或者如果输入错误,则继续提问。
我真正喜欢的方式是使用 sentinel value 因为使用 break
关键字真的让我害怕。
In programming, a special value that is used to terminate a loop. The sentinel value typically is chosen so as to not be a legitimate data value that the loop will encounter and attempt to perform with. For example, in a loop algorithm that computes non-negative integers, the value "-1" can be set as the sentinel value as the computation will never encounter that value as a legitimate processing output.
所以当输入正确时,您可以更改 i 的值,这样您就可以停止循环或以其他方式显示消息并一次又一次地提出问题,直到用户找到正确的答案。
代码:
int i = 0;
Scanner input = new Scanner(System.in);
while (i == 0) {
System.out.println("Enter number zero plz");
int result = input.nextInt();
if(result == 0 ){
System.out.println("I entered right number");
i = 1;
} else
System.out.println("you entered the wrong number \nplz try again");
}
输出:
关于java - 如何检查无效输入并循环直到输入有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27713609/