【发布时间】:2016-01-27 00:18:17
【问题描述】:
问题: 编写一个带有循环的程序,让用户输入一系列非负整数。用户应输入 -99 表示系列结束。除了 -99 作为标记值之外,不接受任何负整数作为输入(实现输入验证)。输入所有数字后,程序应显示输入的最大和最小数字。
问题:执行循环时遇到问题。哨兵值可以跳出循环,但它仍然将该值保留为最小值和最大值。任何人都可以帮助我吗?我是第一次使用并尝试学习 Java。
代码:
import java.util.Scanner;
public class UserEntryLoop
{
public static void main (String [] args)
{
/// Declaration ///
int userEntry = 0, max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
/// Shortcut that shows all of these are int.
/// Integer.Min_VALUE is the lowest possible number for an int
Scanner input = new Scanner(System.in);
// Read an initial data
System.out.print(
"Enter a positive int value (the program exits if the input is -99): ");
userEntry = input.nextInt();
// Keep reading data until the input is -99
while (userEntry != -99) {
// Read the next data
System.out.print(
"Enter a positive int value (the program exits if the input is -99): ");
userEntry= input.nextInt();
}
if (userEntry > max) //// if the max was < X it would print the initialized value.
max = userEntry; /// To fix this the max should be Integer.MAX_VALUE or MIN_VALUE for min
if (userEntry < min)
min = userEntry;
System.out.println("The max is : " + max);
System.out.println("The min is : " + min);
}
}
【问题讨论】:
-
评估
min和max在循环内部。 -
正如@Marvin 指出的那样,您需要在循环中获取涉及
max和min的if条件。 -
我现在把它放在循环中。最大值有效。但是它仍然计算为 -99 的哨兵值的最小值。我该如何解决这个问题?
标签: java