Help with While in Java

Asked

Viewed 137 times

0

I’m starting in Java and I was left with a question about how to insert a While loop in the code below. It’s a simple code I’m doing to practice, but I can’t seem to create While in it. I would like that at the end of the program, he asks if you want to redo, if we type "yes" the program restarts alone, if you type "no", it closes. Down to my code. From now on, thank you and I’m open to suggestions, as I said... I’m beginner in this world of Java and programming, I really want to learn.

package exercicios_java;

import javax.swing.JOptionPane;

public class Par {

    public static void main(String[] args) {

        String numero = JOptionPane.showInputDialog("Por favor digite um número entre 1 e 10: ");
        int num = Integer.parseInt(numero);
        int par = num % 2;

        if (num < 1 || num > 10) {
            String saida = "Por favor, digite um número válido!";
            JOptionPane.showMessageDialog(null, saida);
        } else if (par == 1) {
            String num_impar = "Seu número é ímpar!";
            JOptionPane.showMessageDialog(null, num_impar);
        } else {
            String num_par = "Seu número é par!";
            JOptionPane.showMessageDialog(null, num_par);
        }
    }
}

1 answer

1

While loop allows conditional check at the beginning or end of the instruction block that will be repeated.

Example Loop with check at start:

while(condição){

//bloco de códigos

}

Example Loop with verification at the end:

do{

//bloco de códigos

} while(condição);

In the case that you proposed the ideal would be to make the check at the end of the block of instructions to avoid changing the normal flow of the application (line by line), although While with check at the beginning also work for this case and be the most common use of this loop.

Your code will look something like this:

do{

//todo o código que você quer que repita

String verifica = JOptionPane..showInputDialog("Se desejar refazer digite sim: ");

} while(verifica.equals("sim"));
  • It helped me a lot, I was forgetting to use the DO. .

Browser other questions tagged

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