Loop code with condition not satisfied [closed]

-2
import java.util.Scanner;

public class CodigoDeBarras {
    public static void main (String[] args) {

        do {            

            Scanner sc = new Scanner(System.in);
            System.out.println("Informe os primeiros 12 caracteres do codigo de barras: \n");
            String codigo = sc.nextLine();

        } while (codigo.length() != 12); 
    }
}

I'm trying to get you to repeat the message and read the user's data until it enters a string with an exact 12 characters, but it is giving the following error: "variable is already defined in method main (String [] args)"

    
asked by anonymous 30.08.2017 / 21:38

1 answer

3

The problem is in the scope of the codigo variable. In fact, this code does not compile.

The variable codigo exists only in the scope of do . That way, while(codigo.length() != 12) will not work.

Declare it out and the problem will be solved:

import java.util.Scanner;

public class CodigoDeBarras {
    public static void main (String[] args) {

        String codigo = "";
        do {            

            Scanner sc = new Scanner(System.in);
            System.out.println("Informe os primeiros 12 caracteres do codigo de barras: \n");
            codigo = sc.nextLine();

        } while (codigo.length() != 12); 
    }
}
    
30.08.2017 / 21:46