Call variable in another main

Asked

Viewed 24 times

-2

I no longer know what to do, I need help. I want to print out all customer registrations and saved in public static void clientes(), but for the impression I created a public static void imp(), and when I try to make the call there, it does not, appears in the variable clientes:

"cannot find Symbol".

PF, help me, I need to deliver this by tomorrow.

public static void cliente() {
    CadastroCliente cc = new CadastroCliente(); 
    
    cc.nome = JOptionPane.showInputDialog("Insira o nome do cliente: ");
    cc.CPF = JOptionPane.showInputDialog("Insira o CPF do cliente: "); 
    
    List<CadastroCliente> clientes = new ArrayList<>();
    clientes.add(cc);

}

public static void imp() {
    for (int i = 0; i < clientes.size(); i++) {
        CadastroCliente obj = clientes.get(i);
        JOptionPane.showMessageDialog(null, clientes.toString());
    }            

1 answer

0

You need to take the List<CadastroCliente> clientes = new ArrayList<>(); from within the method cliente(), as written, the variable clientes is with local visibility, ie only within the method. Declare outside the method so that the variable has visibility throughout the class.
Follow a functional example:

import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;

public class variavel_visivel {
    static List<CadastroCliente> clientes;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        clientes = new ArrayList<>();
        cliente();
        cliente();
        imp();
    }
    
    public static void cliente() {
        CadastroCliente cc = new CadastroCliente(); 
        cc.nome = JOptionPane.showInputDialog("Insira o nome do cliente: ");
        cc.CPF = JOptionPane.showInputDialog("Insira o CPF do cliente: "); 
        
        clientes.add(cc);

    }

    public static void imp() {
        for (int i = 0; i < clientes.size(); i++) {
            CadastroCliente obj = clientes.get(i);
            JOptionPane.showMessageDialog(null, "Nome: " + obj.nome +", CPF: "+obj.CPF);
        }
    }
}

Browser other questions tagged

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