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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started