【问题标题】:Sentinel Value Implementation哨兵价值实施
【发布时间】: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);
}
}

【问题讨论】:

  • 评估minmax 在循环内部
  • 正如@Marvin 指出的那样,您需要在循环中获取涉及maxminif 条件。
  • 我现在把它放在循环中。最大值有效。但是它仍然计算为 -99 的哨兵值的最小值。我该如何解决这个问题?

标签: java


【解决方案1】:

您应该在循环中进行测试(我将分别使用Math.minMath.max,而不是ifs 链)。另外,不要忘记检查该值是否为负。类似的,

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

【讨论】:

  • 我试过这个,但最大值和最小值都是一样的。我测试了 1 和 2。最小值和最大值都为 2。
  • 它将最大值和最小值存储为相同的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-11
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多