如何使标记值成为Java中的有效值?

How to make a sentinel value become a valid value in Java?

我的 Java 课本中的一个问题要求我 "Create a new version of the Average program (Listing 3.6) that prevents a runtime error when the user immediately enteres the sentinel value (without entering any valid values)."

清单 3.6 如下:

import java.text.DecimalFormat;
import java.util.Scanner;

public class Average
{
public static void main (String[] args)
{
    Scanner scan = new Scanner (System.in);
    int sum = 0, value, count = 0;
    double average;

    System.out.println ("Enter an integer (0 to quit): ");
    value = scan.nextInt();


    while (value != 0) // sentinel value of 0 to terminate the loop
    {
        count++;
        sum += value;
        System.out.println ("The sum far is " + sum);

        System.out.print ("Enter an integer (0 to quit): ");
        value = scan.nextInt();
    }

    System.out.println ();
    System.out.println ("Number of values entered: " + count);

    average = (double)sum / count;

    DecimalFormat fmt = new DecimalFormat ("0.###");

System.out.println ("The average is " + fmt.format(average));


}
}

我觉得题主想问的是让0的sentinel值被统计。当您输入标记值时,这是清单 3.6 的输出。

输出:

Enter an integer (0 to quit): 
0

Number of values entered: 0
The average is �

此外,我认为与其说 Number of values entered: 0,不如说 Number of values entered: 1。如果你认为你知道问题在问什么,请告诉我。非常感谢您。

你需要一个守卫来确保 count 不等于零。

average = (double)sum / (count == 0 ? 1 : count);

您收到错误消息是因为在您检查了用户的输入后计数才会递增。当第一个数字为 0 时,永远不会进入 while 循环,最终除以 0。问题是要求您修复代码,以避免除以 0 并且不抛出异常。