Tooilia
Tooilia

Reputation: 39

Input compilation error Java

I need int num to only accept numbers. If I input letters I get an error. Is there a way to immediately flag letters, or do I have to take num in as a string and run loops?

import java.util.Scanner;

public class Test 
{        
    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Input a number.");
        int num = input.nextInt();
    }
}

Upvotes: 1

Views: 110

Answers (2)

arshajii
arshajii

Reputation: 129497

You probably want to do something like this:

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

public class Test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Input an integer.");
        int num = 0;  // or any other default value
        try {
            num = input.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("You should've entered an integer like I told you. Fool.");
        } finally {
            input.close();
        }
    }
}

If the user enters something that is not an integer, the code within the catch block will be executed.

Upvotes: 0

vikiiii
vikiiii

Reputation: 9456

You must use Scanner.hasNextInt():

It Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.

public static void main(String[] args) 
 {
 System.out.println("Input a number.");
 Scanner sc = new Scanner(System.in);
 System.out.print("Enter number 1: ");
 while (!sc.hasNextInt()) sc.next();
 int num = sc.nextInt();

 System.out.println(num);

 }

Upvotes: 1

Related Questions