Sentinel价值实施

时间:2016-01-27 00:18:17

标签: java

问题: 编写一个循环程序,让用户输入一系列非负整数。用户应输入-99表示系列结束。除-99作为哨兵值外,不接受任何负整数作为输入(实现输入验证)。输入所有数字后,程序应显示输入的最大和最小数字。

麻烦:无法实施循环。 sentinel值可以退出循环,但仍然保留该值为min和max。有人可以帮我吗?我是第一次使用并尝试学习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);
}
}

1 个答案:

答案 0 :(得分:0)

您应该在循环中进行测试(我分别使用Math.minMath.max,而不是if s链。另外,不要忘记检查值是否为负数。像,

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 >= 0) {
        min = Math.min(min, userEntry);
        max = Math.max(max, userEntry);
    }
}

让我们用数组和单个循环简化问题。

int[] test = { 1, 2 };
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int userEntry : test) {
    min = Math.min(min, userEntry);
    max = Math.max(max, userEntry);
}
System.out.println("The max is : " + max);
System.out.println("The min is : " + min);

我得到了

The max is : 2
The min is : 1