Creating a cycle with a scanner

I am trying to get the scanner to take a number that the user enters, then prints the world hello how many times the user imputes that number with a while loop. I created a scanner for x, I am having trouble finding the correct loop execution.

// import Scanner to take in number user imputs
import java.util.Scanner;

public class HelloWorld {
    public static void main(String[] args){
        // create a scanner class that takes in users number
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter a whole number: " );
        // use x as the number the user entered
        int x = scan.nextInt();
        while ( ){
           System.out.println("Hello World!");
        }
    }
}

      

+3


source to share


5 answers


        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter a whole number: " );
        // use x as the number the user entered
        int x = scan.nextInt();
        while (x > 0){
           System.out.println("Hello World!");
           x--;
        }

      



+3


source


The easiest way is to use a loop for

:

int x = scan.nextInt();
for (int i = 0; i < x; ++i) {
    System.out.println("Hello World!");
}

      



If you absolutely need to use a loop while

, you can simulate the same behavior by declaring as a counter variable ( i

in this case):

int x = scan.nextInt();
int i = 0;
while (i < x);
    System.out.println("Hello World!");
    ++i;
}

      

+2


source


you need to define the true conditon at the time.

 while (x > 0)//true condition.

      

How many times do you want to print a print instruction. In the meantime, there is no need to know about it. ”

 x--;//decrements the value by 1

      

+2


source


Just:

for(int counter = 0 ; counter < x ; counter++) {
   System.out.println("Hello World!");
}

      

Reading the detail is x

completely correct.

+1


source


You can use a loop while

like the following:

Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
while (x > 0){
    // do something
    x--;
}

      

Alternatively, you can also use a loop for

; this is usually the best choice if you know how often the loop will be called before it starts.

0


source







All Articles