-2

I'm trying to make it to were is will throw my exception if the input is not a number and i cant figure it out, Could someone help me get on the right track

import java.util.Scanner;

    class calculations
    {

        public static void main(String[] args)
        {
            Scanner scan = new Scanner(System.in);
            int number;
            int total = 0;
            try
            {

            } catch ( IllegalArgumentException e)
            {
                //error
            }
            while (true)
            {
                number = scan.nextInt();

                if (number == 0)
                {
                    break;
                }
                total += number;
            }
            System.out.println("Total is " + total);
        }

    }
letsintegreat
  • 3,328
  • 4
  • 18
  • 39

1 Answers1

2

You should use hasNextInt, which will allow you to check if the next token in the stream can be parsed as an int.

if (! scanner.hasNextInt()) throw new IllegalArgumentException()
Floegipoky
  • 3,087
  • 1
  • 31
  • 47
  • I haven't programmed in Java in a while, but would that work if the next item were a "." (period) ? – Phil N DeBlanc Mar 22 '18 at 18:26
  • 1
    Yes it should, it is checking if there is an int or not. A '.' is not an int, so hopefully there won't be a problem. – Sean Mar 22 '18 at 18:41