java - 哨兵值(value)实现

标签 java

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

问题:实现循环时遇到问题。哨兵值可以跳出循环,但它仍然保留该值作为最小值和最大值。有人可以帮我吗?我是第一次使用 Java,正在尝试学习 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);
}
}

最佳答案

您应该在循环中进行测试(我将分别使用 Math.minMath.max,而不是一系列 if)。另外,不要忘记检查该值是否不是负数。比如,

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

关于java - 哨兵值(value)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35026557/

相关文章:

java - Java : 0b1000_1100_1010?这样的数字是什么意思(数字之间的 "b")

java - 如何修复无效的 AES key 长度?

java - 相机 Intent 调用 onDestroy()

java - 尝试用对象数组中的 double 值替换字符串

java - BigDecimal 乘法返回 0?

java - 在游戏更新循环中调用延迟 3 秒的函数

java - java中,排序然后对集合进行二分搜索还是线性搜索哪个更有效

java - JSF 应用程序为子上下文提供 404

java - 单个浏览器中的多个 session

Java通知其他线程