Doubt in Try-catch & vector JAVA

Asked

Viewed 49 times

-1

I have the following question:
2. Declare a vector of four positions of the whole data type, the software must remain asking the user to enter a value, until it enters four valid values, the valid values must be stored in the vector.
My progress so far is this:

try
{
    int [] vetor = new int [4];
    System.out.println("Informe o primeiro valor: ");
    vetor[0]=teclado.nextInt();
    System.out.println("Informe o segundo valor: ");
    vetor[1]=teclado.nextInt();
    System.out.println("Informe o terceiro valor: ");
    vetor[2]=teclado.nextInt();
    System.out.println("Informe o quarto valor: ");
    vetor[3]=teclado.nextInt();
    System.out.println("Foram digitados valores válidos.");
}catch(Exception erro)
{
    System.out.println("Valor inválido.");
}

My question is: how to make it request the value until a valid value is entered.

1 answer

0

You can place your Try/catch inside an infinite loop, and let it run until a valid integer is entered:

while (true) try {
    System.out.println("Informe o primeiro valor: ");
    vetor[0] = entrada.nextInt();
} catch (Exception erro) {
    System.out.println("Valor inválido.");
    entrada.next(); // para consumir a entrada atual, que não é válida
}

But as repeating this whole structure for each index would leave the code very polluted, it would be better to organize it within a function, to reuse the code in the next calls:

static Scanner entrada = new Scanner(System.in);

public static void main(String[] args) {
    int[] vetor = new int[4];
    vetor[0] = lerInteiro("Informe o primeiro valor: ");
    vetor[1] = lerInteiro("Informe o segundo valor: ");
    vetor[2] = lerInteiro("Informe o terceiro valor: ");
    vetor[3] = lerInteiro("Informe o quarto valor: ");
}

private static int lerInteiro(String mensagem) {
    while (true) try {
        System.out.println(mensagem);
        return entrada.nextInt();
    } catch (Exception erro) {
        System.out.println("Valor inválido.");
        entrada.next();
    }
}

Browser other questions tagged

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