How to do for instantiating a new JAVA object

Asked

Viewed 348 times

0

I’m in my first object-oriented programming classes and I’m having difficulty with an evaluation.

Create a class with at least 10 attributes for creating objects of the Computer type. The class must have at least 10 constructors methods, access methods (setters and getters) and data entry and display (print) methods. Also create an application that generates at least six objects of the Computer type, using different constructing methods for each created object. Present the results of tests performed in the development environment.

The code I wrote is this, but I’m not able to make each fill the for instates a new object. What I could do to get this done?

import java.text.DecimalFormat;
import java.util.Scanner;

public class AVA1 {
Scanner sc = new Scanner(System.in);

private String placaMae;
private String processador;
private String gabinete;
private String placaDeVideo;
private String mouse;
private String teclado;
private String headset;
private int memoria;
private int monitor;
private double preco;
private DecimalFormat formatador = new DecimalFormat("0.00");
    
public void setPlacaMae(String mob) {
    if (!mob.isEmpty()) {
        this.placaMae = mob;
    } else {
        System.out.println("Fabricante incorreto\n");
        System.out.println("Frabricante da placa mãe: ");
        setPlacaMae(sc.nextLine());
    }
}
public String getPlacaMae() {
    return this.placaMae;
}

public void setProcessador(String cpu) {
    if (!cpu.isEmpty()) {
        this.processador = cpu;
    } else {
        System.out.println("Fabricante incorreto\n");
        System.out.println("Modelo do processador: ");
        setProcessador(sc.nextLine());
   }
}   
public String getProcessador() {
    return this.processador;
}

public void setGabinete(String gab) {
    if (!gab.isEmpty()) {
        this.gabinete = gab;
    } else {
        System.out.println("Fabricante incorreto\n");
        System.out.println("Frabricante do gabinete: ");
        setGabinete(sc.nextLine());
    }
}
public String getGabinete() {
    return this.gabinete;
}

public void setPlacaDeVideo(String vga) {
    if (!vga.isEmpty()) {
        this.placaDeVideo = vga;
    } else {
        System.out.println("Fabricante incorreto\n");
        System.out.println("Modelo da placa de video: ");
        setPlacaDeVideo(sc.nextLine());
    }
}
public String getPlacaDeVideo() {
    return this.placaDeVideo;
}

public void setMouse(String mou) {
    if (!mou.isEmpty()) {
        this.mouse = mou;
    } else {
        System.out.println("Fabricante incorreto\n");
        System.out.println("Modelo do mouse: ");
        setMouse(sc.nextLine());
    }
}
public String getMouse() {
    return this.mouse;
}

public void setTeclado(String tec) {
    if (!tec.isEmpty()) {
        this.teclado = tec;
    } else {
        System.out.println("Fabricante incorreto\n");
        System.out.println("Modelo do teclado: ");
        setTeclado(sc.nextLine());
    }
}
public String getTeclado() {
    return this.teclado;
}

public void setHeadset(String hst) {
    if (!hst.isEmpty()) {
        this.headset = hst;
    } else {
        System.out.println("Fabricante incorreto\n");
        System.out.println("Modelo do headset: ");
        setHeadset(sc.nextLine());
    }
}
public String getHeadset() {
    return this.headset;
}

public void setMemoria(int ram) {
    if (ram >= 1) {
        this.memoria = ram;
    } else {
        System.out.println("Valor inválido, informe um valor acima de 1 GB!\n");
        System.out.println("Quantidade de memória: ");
        setMemoria(Integer.parseInt(sc.nextLine()));
    }
}
public int getMemoria() {
    return this.memoria;
}

public void setMonitor(Integer scr) {
    if (scr > 10) {
        this.monitor = scr;
} else {
    System.out.println("Tamanho do monitor muito pequeno!\n");
    System.out.println("Tamanho do monitor: ");
    setMonitor(Integer.parseInt(sc.nextLine()));
    }
}
public int getMonitor() {
    return this.monitor;
}

public void setPreco(double prc) {
    this.preco = prc;
}
public double getPreco() {
    return this.preco;
}



public class Dados {
    private AVA1 meuComputador;
    public void entradaDados(AVA1 novoComputador) {
        
        
        Scanner sc = new Scanner(System.in);

        for( int i=0; i < 2; i++) { 
        System.out.println("Frabricante da placa mãe: ");
        setPlacaMae(sc.nextLine());

        System.out.println("Modelo do processador: ");
        setProcessador(sc.nextLine());

        System.out.println("Frabricante do gabinete: ");
        setGabinete(sc.nextLine());

        System.out.println("Modelo da placa de video: ");
        setPlacaDeVideo(sc.nextLine());

        System.out.println("Modelo do mouse: ");
        setMouse(sc.nextLine());

        System.out.println("Modelo do teclado: ");
        setTeclado(sc.nextLine());

        System.out.println("Modelo do headset: ");
        setHeadset(sc.nextLine());

        System.out.println("Quantidade de memória: ");
        setMemoria(Integer.parseInt(sc.nextLine()));

        System.out.println("Tamanho do monitor: ");
        setMonitor(Integer.parseInt(sc.nextLine()));

        System.out.println("Preco do Computador: ");
        setPreco(Double.parseDouble(sc.nextLine()));
        System.out.println("");
        
        }
        this.meuComputador = novoComputador;
        sc.close();
    }
    
    public AVA1 imprimir() {
        
        System.out.println("Placa mãe: " + getPlacaMae());
        System.out.println("Processador: " + getProcessador());
        System.out.println("Gabinete: " + getGabinete());
        System.out.println("Placa de video: " + getPlacaDeVideo());
        System.out.println("Mouse: " + getMouse());
        System.out.println("Teclado: " + getTeclado());
        System.out.println("Headset: " + getHeadset());
        System.out.println("Memória ram: " + getMemoria() + "GB");
        System.out.println("Tamanho da tela: " + getMonitor() + "'");
        System.out.println("Preço: R$ " + formatador.format(getPreco()) + "\n\n");
        return this.meuComputador;
    }
}
    
public static void main(String[] args) {
    // TODO Auto-generated method stub
    
    AVA1 meuComputador = new AVA1();
    Dados config = meuComputador.new Dados();
    
    meuComputador.setPlacaMae("Placa Mãe");
    meuComputador.setProcessador("Processador");
    meuComputador.setGabinete("Gabinete");
    meuComputador.setPlacaDeVideo("Placa de Video");
    meuComputador.setMouse("Mouse");
    meuComputador.setTeclado("Teclado");
    meuComputador.setHeadset("Headset");
    meuComputador.setMemoria(1);
    meuComputador.setMonitor(20);
    meuComputador.setPreco(0.00);
    
    config.entradaDados(meuComputador);
    config.imprimir();
    
    }
}

1 answer

1


First, if the class should represent a computer, then I suggest it has a proper name (Computador, maybe? ) - although it seems a silly detail, giving better names helps a lot when programming.

And I wouldn’t need this class Dados inside AVA1. Read here to better understand about Inner classes - It’s a slightly more advanced topic, and since you said you’re in the first few classes, leave it for later. Try to do the simple (because in the first few lessons, they will probably only ask for simple things anyway).

Another point is the separation of responsibilities. Methods setters are at the same time setting the information and asking to type again. I don’t think that the data input should be mixed with the logic of setting/validating a field. The way you did, the code depends on the Scanner (but what if the data comes from somewhere else, like a file, for example?).

So first let’s separate the responsibilities. Create a class Computador, which represents a single computer. It only has the information relating to the computer, and only (the fields, the logic of creation, etc).

public class Computador {
    private String placaMae;
    private String processador;
    ... coloque todos os campos aqui (exceto o Scanner e o DecimalFormat, que não tem nada a ver com o computador em si)

    public String getPlacaMae() {
        return placaMae;
    }

    public void setPlacaMae(String placaMae) {
        this.placaMae = placaMae;
    }

    // demais getters e setters...
}

Print the data

As for printing the data, an option would be for the computer itself to print its data. To do this, create a method in the class itself Computador:

public class Computador {
    // campos, getters, setters, etc..

    public void imprimir() {
        System.out.println("Placa mãe: " + this.placaMae);
        System.out.println("Processador: " + this.processador);
        System.out.println("Gabinete: " + this.gabinete);
        System.out.println("Placa de video: " + this.placaDeVideo);
        System.out.println("Mouse: " + this.mouse);
        System.out.println("Teclado: " + this.teclado);
        System.out.println("Headset: " + this.headset);
        System.out.printf("Memória ram: %dGB\n", this.memoria);
        System.out.printf("Tamanho da tela: %d'\n", this.monitor);
        System.out.printf("Preço: R$ %.2f\n\n", this.preco);
    }
}

Notice the last 3 fields, I used printf instead of concatenating strings, to show that this option exists (in the latter case, I still put %.2f to ensure that the value is displayed to 2 decimal places). View documentation for more details.

If you want, you can also use a NumberFormat to format a monetary value:

public class Computador {
    // campos, getters, setters, etc..

    private static NumberFormat FORMATADOR_PRECO = NumberFormat.getCurrencyInstance(new Locale("pt", "BR"));

    public void imprimir() {
        // imprime os outros campos (igual ao código anterior)
        System.out.printf("Preço: %s\n\n", FORMATADOR_PRECO.format(this.preco));
    }
}

The use of Locale "pt-BR" (Brazilian Portuguese) ensures that the "R$" currency will be used, in addition to using the comma as the decimal separator and the dot to separate the thousands. So the value is printed as R$ 3.599,99 for example.

Like the NumberFormat is static, he is not a field of Computador (a single instance is created for all computers). Read here, here, here and here to better understand.


Create the instances

Having this, you can do your loop create a new computer with each iteration. Something like this:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    for (int i = 0; i < 6; i++) {
        Computador c = new Computador(); // cria um novo computador
        System.out.println("Fabricante da placa mãe: ");
        c.setPlacaMae(sc.nextLine());

        System.out.println("Modelo do processador: ");
        c.setProcessador(sc.nextLine());

        System.out.println("Frabricante do gabinete: ");
        c.setGabinete(sc.nextLine());

        System.out.println("Modelo da placa de video: ");
        c.setPlacaDeVideo(sc.nextLine());

        System.out.println("Modelo do mouse: ");
        c.setMouse(sc.nextLine());

        System.out.println("Modelo do teclado: ");
        c.setTeclado(sc.nextLine());

        System.out.println("Modelo do headset: ");
        c.setHeadset(sc.nextLine());

        System.out.println("Quantidade de memória: ");
        c.setMemoria(Integer.parseInt(sc.nextLine()));

        System.out.println("Tamanho do monitor: ");
        c.setMonitor(Integer.parseInt(sc.nextLine()));

        System.out.println("Preco do Computador: ");
        c.setPreco(Double.parseDouble(sc.nextLine()));

        System.out.println("\n\nCriado o computador:");
        c.imprimir();
    }
}

That is, at the beginning of each iteration I create a computer, then I read the data and set it. And at the end I print the data.

As it is an exercise, I do not know if it is enough (exercises usually have requirements and unusual limitations, so it may not be what the teacher expects). Anyway, it’s not a good example because I create the computer, print the data and then discard it. It would make more sense to store the computers created in an array or list, for example, but since the exercise does not mention any of these, I’ll leave it at that.


Another alternative is to have another class that knows how to print a computer. Something like this:

import java.text.NumberFormat;
import java.util.Locale;

public class Printer {

    private static NumberFormat FORMATADOR_PRECO = NumberFormat.getCurrencyInstance(new Locale("pt", "BR"));

    public static void imprimir(Computador c) {
        System.out.println("Placa mãe: " + c.getPlacaMae());
        System.out.println("Processador: " + c.getProcessador());
        System.out.println("Gabinete: " + c.getGabinete());
        System.out.println("Placa de video: " + c.getPlacaDeVideo());
        System.out.println("Mouse: " + c.getMouse());
        System.out.println("Teclado: " + c.getTeclado());
        System.out.println("Headset: " + c.getHeadset());
        System.out.printf("Memória ram: %dGB\n", c.getMemoria());
        System.out.printf("Tamanho da tela: %d'\n", c.getMonitor());
        System.out.printf("Preço: %s\n\n", FORMATADOR_PRECO.format(c.getPreco()));
    }
}

And in the for just do:

for (int i = 0; i < 6; i++) {
    Computador c = new Computador();
    System.out.println("Fabricante da placa mãe: ");
    c.setPlacaMae(sc.nextLine());
    // lê todos os dados, igual ao anterior

    // na hora de imprimir, usa o Printer, passando o computador criado
    System.out.println("\n\nCriado o computador:");
    Printer.imprimir(c);
}

Validation

If you want to include a validation, an option would be to do this in reading the data:

for (int i = 0; i < 6; i++) {
    Computador c = new Computador();

    // exemplo de leitura do dado
    while (true) {
        System.out.println("Quantidade de memória: ");
        int memoria = Integer.parseInt(sc.nextLine());
        if (memoria >= 1) {
            c.setMemoria(memoria);
            break; // interrompe o while
        } else {
            System.out.println("Valor inválido, informe um valor acima de 1 GB!");
        }
    }
}

Another option is each method Setter throw an exception in case of invalid data, and in reading you check if the error happened, and try again if it is the case:

public class Computador{
    // campos, getters, setters, etc

    // exemplo de setter que valida o dado
    public void setMemoria(int memoria) {
        if (memoria >= 1) {
            this.memoria = memoria;
        } else {
            throw new IllegalArgumentException("Valor inválido, informe um valor acima de 1 GB!");
        }
    }
}

// na leitura dos dados
while (true) {
    try {
        System.out.println("Quantidade de memória: ");
        c.setMemoria(Integer.parseInt(sc.nextLine()));
        break;
    } catch (IllegalArgumentException e) {
        System.out.println(e.getMessage());
    }
}

Builders

As for the fact of creating 10 builders, this is very questionable. In order to satisfy the exercise, it would have to be (imagine) something like this:

public Computador() {} // construtor vazio

public Computador(String placaMae) { // construtor com a placa mãe
    this.placaMae = placaMae;
}

public Computador(String placaMae, String processador) { // com placa mãe e processador
    this.placaMae = placaMae;
    this.processador = processador;
}

etc...

And at the time of creating a computer you could do something like:

System.out.println("Fabricante da placa mãe: ");
String placaMae = sc.nextLine();
Computador c = new Computador(placaMae);
// continua lendo os demais dados...

Or, to use the constructor that receives the motherboard and the processor, store this 2 information in variables and then call the constructor passing them, etc.

But this whole idea is already kind of wrong, in my opinion. Of course, without real requirements, you can only speculate, but does it make sense to create a computer without any configuration? Or just the motherboard, but without all the other information? In a real case, they should only have constructors that make sense (i.e., that create a computer with all the information needed to be a valid instance). As it is an exercise, the requirements in the background are "what the teacher asked for", so if it is to create 10 builders, do what.

The same goes for getters and setters. Not every field needs them. Some you just want to get and can’t change, others may be the other way around. Once you’ve created a computer, can you change the manufacturer’s name? What about the motherboard? The memory maybe (depends on the manufacturer), and so on.

Maybe they are already more "advanced" questions, but anyway, I think it’s important to think about them now, not to get these "vices" to create getters and setters and builders for everything without need. To delve into the subject, read here, here and here.

  • Thank you very much, man, you helped me so much. I’m going to go ahead and read what you suggested. This is a second file I create for testing, so the class name was weird :)

Browser other questions tagged

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