Why is it infinite loop in println?

1
  

Build a program that is capable of averaging all   whole or actual arguments received from the keyboard and print them.

     

Invalid arguments should be disregarded (Print a message   for each invalid value.), without triggering exceptions (Show   message to the user asking him to   value).

     

The user must enter S when you want to close the   data;

I changed S to 5 , but should be S , how do I get a char to read in place? I could not get the logic.

import java.util.Scanner;

public class Media {
    public static void main(String[] args) {

        int i = 0;
        float valor = 0;
        float media = 0;

        Scanner v = new Scanner(System.in);
        valor = v.nextFloat();

        while(valor != 5){
            System.out.println("Insira um valor: ");
            media += valor;
            i++;
        }

        media = valor/i;
        System.out.println("Média é: "+ media);

    }
}
    
asked by anonymous 17.09.2016 / 01:37

1 answer

4

As mentioned by the bigown,

the variable valor never changes within the loop , the condition is never satisfied. Refresh valor at each iteration.

To get a char of the entry, you can do this:

char caractere = v.next().charAt(0);

Alternatively, you can use Scanner.html#hasNext to run the loop until a condition is satisfied, that the%

int i = 0;
float soma = 0, valor = 0, media = 0;
// ....

try (Scanner scanner = new Scanner(System.in)) { // Libera o recurso após o uso
   while (!scanner.hasNext("S")) { // Corre o loop enquanto não for digitado "S"
       System.out.println("Insira um valor: ");

       // Mais códigos...
       i++;
   }
}

Before picking up the input values, make sure the data you want to get is available with S ":

if (scanner.hasNextFloat()) { // Verifica se a entrada pode ser lido como um float
    valor = scanner.nextFloat();
    soma += valor;
}

Out of Scanner.html#hasNextFloat , you output the result as you already do, the other conditions of your exercise, you can easily solve. :)

media = soma / i; 
    
17.09.2016 / 03:10