java - Java中如何使哨兵值成为有效值?

标签 java while-loop sentinel

我的 Java 教科书中的一个问题是要求我“创建一个新版本的 Average 程序( list 3.6),以防止用户立即输入哨兵值(不输入任何有效值)时出现运行时错误。”

list 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被计数。这是当您输入哨兵值时 list 3.6 的输出。

输出:

Enter an integer (0 to quit): 
0

Number of values entered: 0
The average is �

此外,我认为它不是说输入的值的数量:0,而是应该说输入的值的数量:1。如果您认为您知道问题所在,请告诉我。预先非常感谢您。

最佳答案

您收到错误是因为在检查用户的输入之前计数不会增加。当第一个数字为 0 时,永远不会进入 while 循环,最终会被 0 除。问题是要求您修复代码,以避免被 0 除,并且不会引发异常。

关于java - Java中如何使哨兵值成为有效值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40197133/

相关文章:

java - 将对象添加到数组列表 ArrayList<Fitness>

java - 为什么这段代码一直显示错误

exception - 如何在 NLog 中记录网络目标的异常

c - 代码中的错误。我不知道它属于什么类别

css - Primefaces 哨兵固定左侧菜单位置

java - 与 Java 和 Python 相关的 XML 问题

java - Java 中人类可读格式的 SNMP EventTime

C++ 服务器程序 Print While Loop

Java while 循环在与 scan.nextLine() 交互后终止;方法

java - Android工作室: Check object states