Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I have this Java code that works, but I need it to fail if the user enters a letter instead of a number for the

I have this Java code that works, but I need it to fail if the user enters a letter instead of a number for the first input:

package edu.wit.cs.comp1000;

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, 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++;

}

Float avg = (float) sum / (float) count;

if (count == 0)

return 0.00;

else

return avg;

}

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

Database Management System MCQs Multiple Choice Questions And Answers

Authors: Arshad Iqbal

1st Edition

1073328554, 978-1073328550

More Books

Students also viewed these Databases questions

Question

=+4 What are non-union workers representations?

Answered: 1 week ago