Sufyan Sufyan - 3 months ago 37
Java Question

How to handle invalid input when using Scanner.nextInt()

I am a beginner and i wrote a java program that allows you to enter n numbers and it displays the max, min and average only if the number -5 is entered, my program its not displaying correctly and i need some help. I want to use try/catch to catch errors when a string is entered instead integer.

import java.util.Scanner;
public class Average{
public static void main(String[]args){

System.out.print("Enter any integer numbers or -5 to quit:");
Scanner scan =new Scanner(System.in);
double avg = 0.0;
int number = -1;
double avg = 0.0;
double sum = 0;
int count = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;

try {
while((scan.nextInt())!= -5)
{
if (count != 0) {
avg = ((double) sum) / count;
count++;
}
if (number > max){
max = number;
}
if(number < min){
min = number;
}
catch (InputMismatchException e) {
System.out.println("please enter only integer numbers");

System.out.println("Average : " + avg);
System.out.println("maximum : " + max);
System.out.println("minimum : " + min);
}
}
}
}
}

Answer

Try this:

import java.util.Scanner;

public class Average {

static Scanner scan;

public static void main(String[] args) {
    System.out.println("Enter any integer numbers or -5 to quit:");
    scan = new Scanner(System.in);
    int number = -1, sum = 0, count = 0;
    int max = 0;
    int min = 0;
        while((number = scanNextInt()) != -5) {
            count++;
            sum = sum + number;

            if(number > max) {
                max = number;
            }

            if(number < min) {
                min = number;
            }
        }
            if(number == -5) {
                try {
                    System.out.println("Average : " + (sum / count));
                    System.out.println("Maximum : " + max);
                    System.out.println("Minimum : " + min);
                }catch(Exception e) {
                    //Error printing, so quit the program.  Look below.
                }
                //Quit
                System.exit(0);
            }
        scan.close();
    }
    static int scanNextInt() {
        try {
        return scan.nextInt();
        }catch(Exception e) {
            //Stop the program if the user inputs letters / symbols
            System.out.println("Invalid Number.");
            return -5;
        }
    }
}

Changes I've made:
1. I've created a method called scanNextInt() that returns scan.nextInt() if possible. If it will cause an error, it returns -5 to stop the program.
2. I've included the two if statements in the while loop so they actually work.
3. I've caught all of the possible errors, so you should not see any error messages

Note: This HAS been tested