How to read whole numbers with Scanner and handle invalid entries

Asked

Viewed 1,813 times

5

I have the following program, where I need to read a whole, print it out for the System.out

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

Here’s the code I got 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 wish that when the user typed a non-integer, he could have another chance to enter an integer number.

1 answer

6


It won’t work with the nextInt() because it only works if you have already entered a data line, as you are using System.in you have to do it this way:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.