How to declare a vector with 2 positions?

Asked

Viewed 120 times

2

I have an exercise with the following statement:

Write a class whose objects represent students enrolled in a class. Each object in that class must keep the following student data: registration, name, 2 tasting notes and 1 working note. Write the following methods for this class:

media: calculates the final average of the student (each test weighs 2.5 and the job weighs 2)

final: calculates how much the student needs for the final test (returns zero if it is not for the final)

My code is like this:

public class Aluno {
    private String matricula;
    private String nome;
    private double notaProva;
    private double notaTrabalho;

    public void media(double nota1, double nota2) {
        this.notaProva = nota1;
        this.notaTrabalho = nota2;

        double mediaPonderada;
        mediaPonderada = ((this.notaProva*2.5+this.notaTrabalho*2)/(2+2.5));
        System.out.println("Média final: "+ mediaPonderada);
    }
    public void resultadoFinal() {


    }
    public void detalhes() {
        System.out.println("Nome: "+this.nome);
        System.out.println("Matricula: "+ this.matricula);
        System.out.println("Nota da prova: "+ this.notaProva);
        System.out.println("Nota do trabalho: "+ this.notaTrabalho);

    }
    public String getMatricula() {
        return matricula;
    }
    public void setMatricula(String matricula) {
        this.matricula = matricula;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
}
public class PrincipalMain {

    public static void main(String[] args) {
        Aluno aluno = new Aluno();
        aluno.setNome("Magno");
        aluno.setMatricula("20194456458");
        aluno.media(9, 5);
        aluno.detalhes();           
    }    
}

How do I declare an array in the attribute notaProva with 2 positions?

2 answers

4


To define that the type of a variable is a array it is necessary to use brackets, for example:

private double[] notasProvas;

Java cannot declare a array and already set the number of positions. The size always needs to be set at startup.

In your case, I imagine the best output is to define a constructor for the class and initialize the array in this builder.

public class Aluno {
    // ... outros campos

    private double[] notasProvas;

    public Aluno() {
        notasProvas = new double[2];
    }
}

Of course, after this, you will need to think about how the structure of(s) getters and setters.

0

When you want to declare an array, use square brackets. Example: double vetor1 [];

By declaring its size and content, you can directly enter the data as follows: vetor1 = {x1, x2};

Or you can create an empty vector, and fill it during program execution: vetor1 = new double[2];

I hope I’ve helped

Browser other questions tagged

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