Why does it loop infinitely in the println?

Asked

Viewed 146 times

1

Build a program that is able to average all entire or actual arguments received from the keyboard and print them.

Invalid arguments should be disregarded (Print a message for each invalid value. ), without triggering exception display (Display a message to the user asking him to inform again the value).

The user must enter S when they wish to terminate the entry dice;

I switched the S for 5, but it must be S, how do I get to read a char in place? I couldn’t 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);
        
    }
}
  • You can use Wrappers?

  • 6

    The loop infinite occurs because the valor never changes inside the loop, so there is no way out. This answers the title question. The question of the question body is completely different from the title and to solve this you have to redo almost every code.

1 answer

4


Like mentioned by Maniero, the variable valor never changes inside the loop, the condition is never satisfied. Update valor at each iteration.

To get a char from the entrance, you can do so:

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

Alternatively, you can use Scanner.html#hasNext to run the loop until a condition is met, that the letter be typed S:

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 Scanner.html#hasNextFloat:

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

Outside the try, you display the result as you are already doing, the other conditions of your exercise, you can easily solve. :)

media = soma / i; 
  • If you can from the ruma look below kindly, I have the following doubt... (I added as an answer)

Browser other questions tagged

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