Variable within FOR - Java

0

I get 0 in the variables contApproved and contSuspendido at the end of the for. How can I do to obtain the result I accumulate in the for?

   import java.util.Scanner;
class NotaDeClase{
    private double nota;
    private static Scanner sc = new Scanner(System.in);

    public void setNota(){
        nota=sc.nextDouble();
    }

    public void notasClase(){

        int contSuspendido=0;
        int contAprobado=0;
        int i;

        for (i=0;i<3;i++){

            System.out.println("Introduce nota: ");
            setNota();

            if (nota>=5) contAprobado=contAprobado++;
            else     contSuspendido=contSuspendido++;

            while (nota>10 || nota<1){
                System.out.print("Nota invalida, introduce nota valida: ");
                setNota();
            }
        }

        System.out.println("Nº APROBADOS: "+contAprobado);
        System.out.println("Nº SUSPENSOS: "+contSuspendido);

    }

    public static void main(String[] args) {
        NotaDeClase a = new NotaDeClase();
        a.notasClase();
    }
}
    
asked by David 01.11.2017 в 17:30
source

3 answers

2

Just leave contAprobado++ and contSuspendido++ . That will be enough for the code to work as you want.

    
answered by 01.11.2017 / 17:41
source
1

When you type "++" to the right of a variable, you are running a POST-increment. This means that the increase is made AFTER using the variable.

When you do contApproved = contApproved ++ you are not doing anything. The variable stays with the same value it had. This is because "contApproved ++" returns 0 (its previous value), and subsequently it increases, but that 0 is saving it in the same variable, therefore, the result is that it always remains in its initial value, that is, 0.

You have several solutions:

Execute a PRE-increment (first performs the increment, and then returns the value of the variable):

contAprobado=++contAprobado;

Use simply, post-growth:

contAprobado++;

Or add 1 to the variable:

contAprobado += 1;
    
answered by 04.11.2017 в 00:48
1

Try This

contAprobado=contAprobado++;

contSuspendido=contSuspendido++;
    
answered by 01.11.2017 в 17:48