Prime Numbers in JAVA

Asked

Viewed 621 times

5

I’m doing a job in Java, where the user must enter numbers smaller than 20, and then this program must tell which numbers are prime. I don’t know if my logic is right, but on the console nothing appears, it’s just empty.

Follows the code:

package javatrabalho;

import javax.swing.JOptionPane;

public class trabalhopronto {

public static void main(String[] args) {
    String entrada1;
    int numero, contador;
    numero = 0;
    contador = 1;

    if (numero > 20) {
        System.out.println("Informe um numero menor que 20");
    }

    while (numero <= 20) {

        entrada1 = JOptionPane.showInputDialog("Informe um numero menor que 20");
        numero = Integer.parseInt(entrada1);

        // saber se um numero é primo
        if (numero < contador) {

            if (numero % contador == 0) {
                contador = contador + 1;
            }

            if (contador > 2) {
                System.out.println("O numero é primo" + numero);
            } else {
                System.out.println("O numero não é primo" + numero);
            }

        }

    }

}

}
  • 1

    Besides the problem of contador Already quoted in André’s answer below, the algorithm to determine if the number is prime is not correct. There are several algorithms for this, some more naive (make a for 1 in 1 to n), and a little more "smart" (example: https://stackoverflow.com/a/31111675)

  • I also found a reply on prime numbers, a check

1 answer

3


Hello ayanami001, welcome to en.stackoverflow.com.

I analyzed your code and noticed that the problem is in the following condition:
if (numero < contador) { ...

I don’t know if you noticed, but when starting the application, the variable contador is being initialized with the value 1 and whenever you enter a higher value than 0 and less than or equal to 20, the application will never go through that code block inside the if cited above. This explains why your application does not display anything on your console in this scenario.

Tip: I also noticed you not using one of the Java class naming rules and conventions ¹(all class should start with a capital letter and preferably cannot contain non-ASCII letters) in your project, of course this will not prevent the execution of your Java class, however I advise you to start adapting to these details which are extremely important.

  • 2

    I wouldn’t call it a rule but a convention,.

  • I agree Isaac, thanks for opining on this detail. The term rule implies that there is only the possibility such a way :)

Browser other questions tagged

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