1

I've been instructed to create a code that takes a user's first 5 inputs (doubles) and finds the average. My only problem is creating an exception if a user inputs anything other than a number. Could someone show how I can add this exception to my code?

import java.util.*;

public class Test1
{
   static Scanner userInput = new Scanner(System.in);

public static void main(String[] args)
{
    Scanner numbers = new Scanner(System.in);

    System.out.println("Please enter a number: ");
    double first = numbers.nextInt();

    System.out.println("Please enter a number: ");
    double second = numbers.nextInt();

    System.out.println("Please enter a number: ");
    double third = numbers.nextInt();

    System.out.println("Please enter a number: ");
    double fourth = numbers.nextInt();

    System.out.println("Please enter a number: ");
    double fifth = numbers.nextInt();

    System.out.println("The average is\t" + ((first + second + third + fourth + fifth)/5)+"\t");
   }
}
Pavneet_Singh
  • 34,557
  • 5
  • 43
  • 59
  • either use `try` block or you can use `hasNextInt` along with `if` , make sure to flush unwanted input – Pavneet_Singh Oct 15 '16 at 15:54
  • Possible duplicate of [Validating input using java.util.Scanner](http://stackoverflow.com/questions/3059333/validating-input-using-java-util-scanner) – Tom Oct 15 '16 at 17:41

1 Answers1

0

This will handle the user typing non Integers.

It also removes the static Scanner userInput which isn't being used.

public class HelloWorld
{
    public static void main(String[] args)
    {
        Scanner numbers = new Scanner(System.in);

        int total =0;
        int numberOfQuestion = 5;

        for (int i = 0; i < numberOfQuestion ; i ++) {
            System.out.println("Please enter a number: ");

            while (!numbers.hasNextInt()) {
                System.out.println("Input was not a number, please enter a number: ");
                numbers.next();
            }

        total = total + numbers.nextInt();

        }

        System.out.println("The average is\t" + (total/numberOfQuestion)+"\t");
    }
}
UserF40
  • 3,129
  • 2
  • 19
  • 31