I am trying to make it so a scanner takes in the number the user enters then prints hello world for how many times the user has imputed that number using a while loop. I created a Scanner for x, I am having trouble finding out how to properly execute the loop though.
// 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!");
}
}
}
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--;
}
The easiest way would be to use a for loop:
int x = scan.nextInt();
for (int i = 0; i < x; ++i) {
System.out.println("Hello World!");
}
If you absolutely have to use a while loop, you can simulate the same behavior by declaring a counter variable (i, in this case) yourself:
int x = scan.nextInt();
int i = 0;
while (i < x);
System.out.println("Hello World!");
++i;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With