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!");
}
}
}
source to share
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;
}
source to share
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.
source to share