Make variable wait to be set by user after While? java

Asked

Viewed 186 times

0

Hello, I want the user to set the value of a variable, but it should set it only after the while. My question is, how do you do it? Here’s the piece I’m doubting.

public static void chama_programa(){

    Scanner sc = new Scanner(System.in);
    int num;

   while (!(num < 1000)){
       System.out.println("Escreva um numero menor que 1000");
      num = sc.nextInt();

Because the way this one says that the variable one needs to be initialized while direct without giving chance to be typed.

2 answers

0

I don’t quite understand your question. But come on: Start the variable with the value 0, to prevent excerpts where it will not be used.

    int num = 0;
       do {
         System.out.println("Escreva um numero menor que 1000");
         num = read.nextInt();
         if (num > 1000) {
           System.out.println("Erro! Numero invalido!");
         }
       }
       while (num > 1000);
    }

In this case, while will test the error, if the number is greater than 1000, it will repeat the message, and after exiting while, it will keep the value of the variable. I hope I’ve helped

  • This actually did not work because, as I wrote, when I start it with any number including zero the program goes straight without asking the user to type.

  • Well, then there must be some other error in your code. put the full code please.

0

I believe the intent of your code is to force the user to enter a number less than 1000.

Being for there are two solutions:

The first solution is simpler than starting num 1000 and change the iteration condition to a condition that checks whether num is greater than or equal to 1000:

   int num = 1000;

   // como num é inteiro poderia ser (num > 999). 
   while (num >= 1000) { 
       System.out.println("Escreva um numero menor que 1000");
       num = sc.nextInt();
   }

The second solution is to transform the loop while in a loop do-while and change the iteration condition to a condition that checks whether num is greater than or equal to 1000:

do {
      System.out.println("Escreva um numero menor que 1000");
      num = sc.nextInt();
} while (num >= 1000) // como num é inteiro poderia ser (num > 999).

Browser other questions tagged

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