Benjamin Ryan Benjamin Ryan - 1 month ago 16
Java Question

I need help and am stuck, i am new to java programming

I am stuck, I need to Design and then implement a program that reads a series of 5 doubles from the user and prints their average. Read each input value as a string, and then attempt to convert it to a double using the Double.parseDouble method. This method will throw an exception if the parameter given to it cannot be parsed. Read the online documentation to determine what exception should be caught. If this exception occurs (meaning that the input is not a valid number), print an appropriate error message and prompt for the number again. Continue reading values until 5 valid doubles have been entered. Please help.

public class Homework1 {

public static void main(String[] args) {
int numlength = 5;
int i = 0;
double total = 0;
Scanner sc = new Scanner(System.in);
boolean done = false;
do {
try (int num1 = 0; num1< numlength; num1++) ;
{
System.out.print("Please enter an Integer: ");
total += sc.nextInt();
}
done = true;
} catch (InputMismatchException e) {
System.out.println("This is not an Integer.");
}
} while (!done);

System.out.printf("You entered %d\n", i);
System.out.println("The Average is: " + (total / numlength));
}

}

Answer

Let me first point out your mistakes:

  1. try is not a function,its a block,
    it opens and closes with curly braces.
  2. you are using try block as a for loop, please take care of it
  3. System.out.printf("You entered %d\n", i);
    this line at the end of loop will only print 5, i.e. the final value of i. It will not print the inputs that you have entered(as i guess you intend to).


This will help you:

import java.util.InputMismatchException;
import java.util.Scanner;

public class Debug {

    public static void main(String[] args) {
        int numlength = 5;
        int i = 0;
        double total = 0;
        Scanner sc = new Scanner(System.in);
            try{ 
                do{
                     System.out.print("Please enter an Integer: ");
                     total += sc.nextInt();
                     i++;
                }while(i<numlength);
                System.out.println("The Average is: " + (total / numlength));
            }
             catch (InputMismatchException e) {
                System.out.println("This is not an Integer.");
            }         
    }

}