0

I am trying to validate that the user only enters an integer. Is there another way to do this that will make the validation more simplified?

Scanner in = new Scanner(System.in);
System.out.print("Enter the amount of subjects that you need to get an average of: ");
int amount_of_subjects;
    
while (!in.hasNextInt())
{
  // warning statement
  System.out.println("Please Enter integer!");
  in.nextLine();
}
 
amount_of_subjects = Integer.parseInt(in.nextLine());
Andreas Hacker
  • 221
  • 1
  • 11

3 Answers3

2

Depending what you want to do with your program.

If you want to only take a valid Integer as input you can use the nextInt() function

Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();

If you want to check if the user is putting in a valid Integer to respond to that you can do something like:

public boolean isNumber(String string) {
    try {
        Integer.parseInt(string);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}
Lucas Kok
  • 44
  • 4
2

It seems your solution is already quite simple. Here is a more minimalist version:

System.out.print("Please enter an integer: ");
while(!scan.hasNextInt()) scan.next();
int demoInt = scan.nextInt();

from https://stackoverflow.com/a/23839837/2746170

Though you would only be reducing lines of code while possibly also reducing readability.

Andreas Hacker
  • 221
  • 1
  • 11
0

Here is an easier approach which validates integer values 0 - max value inclusive and type checks the user input and finally displays result or error message. It's looped over and over until good data is received.

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


class Main {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int userVal = 0;
        
        while(true){
            
            try{
                System.out.print("Enter a number: ");
                userVal = scan.nextInt();

                if ((userVal >= 0 && userVal <= Integer.MAX_VALUE)){
                    System.out.println(userVal);
                    break;
                }
            }
            catch(InputMismatchException ex){
                System.out.print("Invalid or out of range value ");
                String s = scan.next();
            }           
        } 
    }
}
pauan
  • 49
  • 5