Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a loop with a Scanner

Tags:

java

loops

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!");
        }
    }
}
like image 417
Supdawg Avatar asked Aug 26 '26 10:08

Supdawg


2 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--;
        }
like image 96
Thusitha Thilina Dayaratne Avatar answered Aug 29 '26 00:08

Thusitha Thilina Dayaratne


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;
}
like image 27
Mureinik Avatar answered Aug 28 '26 23:08

Mureinik