我必须编写一个完整的Java程序,提示用户输入一系列数字以确定输入的最小值。在程序终止之前,显示最小值。我必须使用此代码并完成运行程序的信息:
这是代码:
Scanner keyboard = new Scanner(System.in);
int smallest = 9999999;
String user_Input;
boolean quit = false;
System.out.println("This program finds the smallest number"
+ " in a series of numbers");
System.out.println("When you want to exit, type Q");
while(…………..)
{
System.out.print("Enter a number: ");
user_Input = keyboard.next();
if(user_Input.equals("Q")……….. user_Input.equals("q"))
{
quit = true;
}
………..
{
int user_Number = Integer.parseInt(user_Input);
if(……………………)
smallest = user_Number;
}
}
System.out.println("The smallest number is " + smallest);
System.exit(0);
}
}
答案 0 :(得分:-1)
这只是读取并尝试解析数字,如果失败,那么它只是转移到while循环的守卫。
此外,您应该尝试使用Integer.MAX_VALUE而不是随机数。以防有人决定实际使用最大值;不要假设9,999,999或者你想要多少9个是最大的
有关最大值的更多信息:https://en.wikipedia.org/wiki/2147483647_(number)
Scanner keyboard = new Scanner(System.in);
int smallest = Integer.MAX_VALUE;
String input = "";
System.out.println("This program find the smallest number"
+ " in a series of numbers");
System.out.println("When you want to exit, type Q");
while (!input.toLowerCase().equals("q")) {
System.out.print("Enter a number: ");
input = keyboard.next();
try {
int numb = Integer.parseInt(input);
if (numb < smallest)
smallest = numb;
} catch (NumberFormatException e) {
// Maybe check for other random strings here?
// If you expect only "Q" or a number, then no need
}
}
System.out.println("Smallest number: " + smallest);
System.exit(0);