Question: I have this java code that works, but I need to figure out a way to make it output 0.00 when I input a single

I have this java code that works, but I need to figure out a way to make it output 0.00 when I input a single negative number. It asks the user for a series of non-negative numbers and then they enter a negative number to signal the ending of their sequence. However, I need it to output 0.00 instead of NaN if the user inputs -1 and no other number.

Code:

import java.util.Scanner;

public class PA5b {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String ch = "";

do {

double avg = getAverage(sc);

System.out.printf("The average is: %.2f%n" , avg);

System.out.println("Do you want to compute another average (y/n)?");

sc.nextLine();

ch=sc.nextLine();

} while (!ch.equalsIgnoreCase("N"));

}

private static double getAverage(Scanner aSc) {

double sum = 0.00;

double count = 0.00, num = 0.00;

System.out.println("Enter a stream of non negative numbers (negative number when finished): ");

while (true) {

num = aSc.nextDouble();

if (num < 0)

break;

sum += num;

count++;

}

return sum / count;

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!