Help with an exercise where Do Implement

1

Good I need help the following code is not doing the evaluation of if after asking its continue it returns to the beginning of the loop.

import java.util.Scanner;

public class EjercicioCinco {

    public static void main(String[]args){

        Scanner sc = new Scanner(System.in);
        boolean continuamos = true;
        int auxNota = 0;
        int i = 0;
        String respuesta;

        do {

            System.out.println("Ingrese la nota");

            int nota = sc.nextInt();

            auxNota += nota;

             i++;

            System.out.println("Continuamos?");

            respuesta = sc.nextLine();

            if (respuesta == "n") continuamos = false;

        }while(continuamos);

        System.out.println("El Promedio de notas es : "+(auxNota/i));

    }

}
    
asked by Maxi Hernandez 02.05.2017 в 13:04
source

1 answer

1

I think you have two mistakes:

1- when comparing string, look at this question which has several answers about comparing string.

2- after reading an integer for example, and after wanting to read a string you have to clean the buffer (looking for a question that explains it)

well I did not find it, but you have to delete the buffer, for example with nombre_de_su_scanner.nextLine(); before taking the string some string, because if you previously obtained a numeric data "it stays" in the buffer \n \s\ or any return which may cause it to not work well, because the methods nextInt(); or any nextX, do not consume the above, except .nextLine(); for example, so we use that method call to clean the buffer of the scanner

now change * respuesta == "n" by respuesta.equals("n") and add sc.nextLine(); before respuesta = sc.nextLine();

import java.util.Scanner;

public class EjercicioCinco {

    public static void main(String[]args){

   Scanner sc = new Scanner(System.in);
    boolean continuamos = true;
    int auxNota = 0;
    int i = 0;
    String respuesta;

    do {

        System.out.println("Ingrese la nota");

        int nota = sc.nextInt();

        auxNota += nota;

         i++;

        System.out.println("Continuamos?");

        sc.nextLine();
        respuesta = sc.nextLine();

        if (respuesta.equals("n")) continuamos = false;

    }while(continuamos);

    System.out.println("El Promedio de notas es : "+(auxNota/i));

    }

}

Test:

Ideone.com

P.D: If you are doing the evaluation of if but for what is mentioned in the previous points it does not do what you expect.

    
answered by 02.05.2017 в 14:06