How to read integers with Scanner and handle invalid entries

5

I have the following program, where I need to read an integer, print it to System.out

However, in my code, when the program receives an invalid value as a String, I want to report the error to the user and still expect to receive an integer.

Here is the code I have today:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner entrada = new Scanner(System.in);

        while(true){
            System.out.printf("Entre com um número inteiro qualquer: ");

            try{
                int inteiro = entrada.nextInt();
                System.out.printf("Eis a aberração: %d", inteiro);
            }

            catch(Exception e){
                System.out.printf("Você não digitou um número inteiro!");
            }
        }
    }
}

I would like that when the user types a non-integer, he might have another chance to type an integer.

    
asked by anonymous 30.06.2015 / 16:58

1 answer

6

It will not work with nextInt() because it only works if you have already entered with a row of data, as you are using System.in you have to do this:

Scanner entrada = new Scanner(System.in);

while(true){
    System.out.printf("Entre com um número inteiro qualquer: ");
    String linha = entrada.nextLine(); // ler a linha (termina no enter)

    try{
        int inteiro = Integer.parseInt(linha); // (tenta converter pra int os dados inseridos)
        System.out.printf("Eis a aberração: %d\n", inteiro);
    }

    catch(Exception e){
        System.out.printf("Você não digitou um número inteiro!\n");
    }
}


Example of nextInt()

String s = "Hello World! 123 ";
Scanner scanner = new Scanner(s);

while (scanner.hasNext()) {
    System.out.println("entrou");
    if (scanner.hasNextInt()) {
        System.out.println("Eis a aberração: " + scanner.nextInt());
    } else {
        scanner.next();
    }
}
scanner.close();
  

123

    
30.06.2015 / 17:06