How could I make sure that the text is not duplicated

Asked

Viewed 40 times

-2

I was developing a Java application that basically creates a 4 x 4 matrix, which has to count and write how many values greater than 10 it has, until I was able to do this, but the text that asks the user to type two values (the one in the row and the one in the column) always appears duplicated, I’ve tried to do many things, but it didn’t help much.

Program code:

import java.util.Scanner;

public class main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int contagem = 0;

        int matriz[][] = new int [4][4];

        for (int linha = 0; linha < 4; linha++) {
            for (int coluna = 0; coluna < 4; coluna++) {
                System.out.println("\nInsira dois numeros, um para a coluna e outro para a linha = ");
                matriz[linha][coluna] = sc.nextInt();
                
                if (matriz[linha][coluna] > 10) {
                    contagem++;
                }
            }
        }

        System.out.println("Na matriz existem: " + contagem + " numeros maiores que 10");
    }
}

Problema

1 answer

-1


sc.nextInt() reads only one number, but you are asking the user to type 2.

The second number the user enters will continue in the buffer, and the next time you invoke sc.nextInt(), it will read this second number immediately, so the program does not even prompt the user to enter a number again, it prints Insira dois numeros, um para a coluna e outro para a linha = and captures the second number that has already been typed.

But the program is right, just what you’re asking for as input is giving the wrong impression. You should be asking the user to enter a single value for the current row/column.

Instead of

System.out.println("\nInsira dois numeros, um para a coluna e outro para a linha = ");

It would make more sense to ask

System.out.println("\nInsira um número para a posição ["+linha+"]["+coluna+"] = ");
  • thanks a lot bro, I’m just finding it strange that when I put to run the program in the terminal, appears twice the text asking to inform two values

  • It appears because the user has entered 2 numbers. If the user type 3, then 3 messages will appear, for reasons explained in the reply.

  • then how would I solve it?

  • Okay, it worked out here, thank you :)

Browser other questions tagged

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