How to use Scanner to define the characteristics of the "product" object

Asked

Viewed 22 times

0

   public static void cadastrarProduto(String nome, int codigo, int quantidade, double valor) {
    var produto = new Produto();
    Scanner leitor = new Scanner(System.in);
    nome = leitor.next();
    produto.nome = nome;
    nome = leitor.next();
    produto.codigo = codigo;
    codigo = leitor.nextInt();
    produto.quantidade = quantidade;
    quantidade = leitor.nextInt();
    produto.valor = valor;
    valor = leitor.nextDouble();
    produtos.add(produto);
}

}

  • Please edit the question to limit it to a specific problem with sufficient detail to identify an appropriate answer.

1 answer

1

From what I understand of the code has only one logic error. What confused a little was the fact of having declared parameters in the method cadastrarProduto().

Another thing is that tried to make a direct assignment to class attributes Produto (this only works if the attributes are declared as public in class Produto), when you should actually use the setters (or constructor). This is known as encapsulation.

I just refactored your code to try to do what is described in the title, I used the scanner to define the characteristics of the product object.

Follow the refactored code:

public static void cadastrarProduto() {
    var produto = new Produto();
    Scanner leitor = new Scanner(System.in);
    
    String nome = leitor.next();
    produto.setNome(nome);

    int codigo = leitor.nextInt();
    produto.setCodigo(codigo);

    int quantidade = leitor.nextInt();
    produto.setQuantidade(quantidade);

    double valor = leitor.nextDouble();
    produto.setValor(valor);

    produtos.add(produto);
}

Browser other questions tagged

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