Learning_Java Learning_Java - 28 days ago 13
Java Question

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

One of the questions from my Java textbook is asking me to "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)."

Listing 3.6 is below:

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));


}
}


I think what the question is asking is to make the sentinel value of 0 to be counted. Here is the output of Listing 3.6 when you type in the sentinel value.

Output:

Enter an integer (0 to quit):
0

Number of values entered: 0
The average is �


Additionally, I think that instead of it saying
Number of values entered: 0
, I think it is suppose to say
Number of values entered: 1
. If you think you know what the question is asking, please let me know. Thank you very much in advance.

Answer

You need a guard to make sure count is not equal to zero.

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