1

I am trying to get a user to input an integer, which will be used in mathematical equations. If the user inputs anything besides an integer, the input must be discarded and a warning given to the user. In short, I need a way to test if an input is an integer or not, and if not, then display a warning and stop the program before the input creates errors. Below is a snippet of my code; I tried to use a .hasNextLine to test if the input is a string, but even without input it returns as true and prints the warning message.

System.out.println("Input integer");
if(stdin.hasNextLine()) { //This line to test if the input is not integer
System.out.println("Input invalid, enter an integer"); //This line to give the user a warning that the input is invalid (not an integer)
System.exit(0); //This line to exit the program before the non-integer input messes with later code
}//close test

SOLVED Used .hasNextInt to test for an integer, and if true proceed, if false print warning and end program. -Courtesy of shmosel

Walshy231
  • 9
  • 2

1 Answers1

0

Maybe this is not the most optimised solution, but should work as you need:

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

public class MyClass {
    public static void main(String args[]) {
        System.out.println("Please type an integer:");

        Scanner scanner = new Scanner(System.in);
        Integer result = null;
        while(result == null && scanner.hasNext()) {
            if(scanner.hasNextInt()) {
                result = scanner.nextInt();
            } else {
                scanner.next();
                System.out.println("Wrong input, please type valid integer!");
            }
        }

        System.out.println("Thanks, you typed valid Integer " + String.valueOf(result));

    }
}
Passarinho
  • 109
  • 1
  • 2
  • 15