How to call a method inside a System.out.println?

2

Can you call a method within a System.out.println(" "); ?

Follow my code:

package ExerciciosReferenciaDeObjetos;

    public class Aluno {
        private String nome;
        private int matricula;
        private float n1,n2,media;




    public void Aluno(String nome, int matricula, float n1, float n2){
        this.nome=nome;
        this.matricula=matricula;
        this.n1=n1;
        this.n2=n2;
    }

    public void  Media(float n1, float n2){
        float Media;
        Media= (n1+n2)/2;
    }


    public void Exibir(){
        System.out.println("Nome:"+this.nome);
        System.out.println("Matrícula:"+this.matricula);
        System.out.println("Nota 1:"+this.n1);
        System.out.println("Nota 2:"+this.n2);
        System.out.println("A média é:"+this.media()); /**no caso estou querendo chamar o método da média dentro do system.out... , mas está dando erro**/ 


    }
    
asked by anonymous 13.05.2017 / 22:23

2 answers

5

The code has several errors. There is the name of the method that is declared as uppercase, which is not ideal and is calling lowercase. It is receiving parameters that are not necessary, but in the call it does not use them. Not returning a value and only then can you use this value somewhere else. The builder is also wrong. I improved some more things.

class HelloWorld {
    public static void main (String[] args) {
        Aluno aluno = new Aluno("joao", 1, 8f, 6f);
        aluno.exibir();
    }
}

class Aluno {
    private String nome;
    private int matricula;
    private float n1, n2;

    public Aluno(String nome, int matricula, float n1, float n2) {
        this.nome = nome;
        this.matricula = matricula;
        this.n1 = n1;
        this.n2 = n2;
    }

    public float media() {
        return (n1 + n2) / 2;
    }

    public void exibir() {
        System.out.println("Nome:" +nome);
        System.out.println("Matrícula:" + matricula);
        System.out.println("Nota 1:" + n1);
        System.out.println("Nota 2:" + n2);
        System.out.println("A média é:" + media());
    }
}

See running on ideone . And No Coding Ground . Also put it on GitHub for future reference .

    
13.05.2017 / 22:35
1

Yes, there is but in this case it will not work because your methods are like void you would have to put the methods of the msm type of the return of it and is clado add a return, I will show you what the media class would look like

public float  Media(float n1, float n2){
float Media;
Media = (n1+n2)/2;
return Media;
   }
    
13.05.2017 / 22:31