Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Modern Database Management

Authors: Donald A. Carpenter Fred R. McFadden

1st Edition

8178088045, 978-8178088044

More Books

Students also viewed these Databases questions

Question

Explain the various techniques of Management Development.

Answered: 1 week ago

Question

=+j Describe the various support services delivered by IHR.

Answered: 1 week ago

Question

=+j Explain IHRMs role in global HR research.

Answered: 1 week ago

Question

=+j Describe an effective crisis management program.

Answered: 1 week ago