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());

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks does the Integer.parseInt(in.nextLine()) need to be used instead?
@Nexus_Valentine Exceptions shouldn't be used for checks like these, see Effective Java Item 69, discussed here ahdak.github.io/blog/effective-java-part-9
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;
    }
}

Comments

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();
            }           
        } 
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.