How to use Try with while and vectors

Asked

Viewed 68 times

2

I need to create a code where the user enters 4 whole numbers and if anything else is typed an exception treatment.

I’m having problems with the catch, I’m not able to do that when the exception occurs it goes back to while without counting the controller for, or it is necessary for the 4 numbers to be integer and not to leave the program until they are completed correctly.

import java.util.Scanner;

public class Teste {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int [] vet = new int[4];
        
        boolean erro = true;
        
        for(int i=0;i<=3;i++) {
            erro = true;
            while (erro == true) {
                try {
                    System.out.println("Informe o " + (i+1) + "º numero: ");
                    vet[i] = sc.nextInt();
                }
                catch(Exception e){
                    System.out.println("Valor inválido");
                    
                    
                }
                erro = !erro;
            }
        }
        
    }

}

1 answer

2


You don’t need this complex code. You can just go back on the count of for when it gives error. But that alone does not solve the whole problem. Note that I switched to capture the specific exception and cleared the buffer of scanner that keeps that data when it gives error (a Java flaw in my opinion, but you have to deal). And improved a few more points.

import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int [] vet = new int[4];
        for (int i = 0; i < 4 ; i++) {
            try {
                System.out.println("Informe o " + (i + 1) + "º numero: ");
                vet[i] = sc.nextInt();
            }
            catch (InputMismatchException e) { //note que eu capturei a exceção certa
                System.out.println("Valor inválido");
                sc.nextLine(); //precisa disso pra limpar o buffer
                i--;
            }
        }
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thanks Maniero! Really got much cleaner so and the part of cleaning the tb buffer helped a lot! Had made some changes and in one of them the catch kept picking up the error and repeating until the end of the for, I believe that this occurred for not having used this "morning".

Browser other questions tagged

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