Reputation: 61
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!");
}
}
}
Upvotes: 3
Views: 483
Reputation: 3757
You could use a while
loop such as the following one:
Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
while (x > 0){
// do something
x--;
}
Alternatively you could also use a for
loop; this is usually the best choice if you know how often the loop will be called before it starts.
Upvotes: 0
Reputation: 1540
you have to define a true conditon in while.
while (x > 0)//true condition.
How many time will you like to print your print statement.
x--;//decrements the value by 1
Upvotes: 2
Reputation: 5712
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--;
}
Upvotes: 3
Reputation: 312404
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;
}
Upvotes: 2
Reputation: 53879
Simply:
for(int counter = 0 ; counter < x ; counter++) {
System.out.println("Hello World!");
}
The part reading x
is perfectly correct.
Upvotes: 1