Question
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
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