使用扫描仪创建循环

时间:2014-09-08 15:47:20

标签: java loops

我正在努力使扫描仪接收用户输入的数字然后打印问候世界用户使用while循环估算该数字的次数。我创建了一个扫描仪x,我很难找到如何正确执行循环。

// 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!");
        }
    }
}

5 个答案:

答案 0 :(得分:3)

        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--;
        }

答案 1 :(得分:2)

最简单的方法是使用for循环:

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

如果你必须使用while循环,你可以通过自己声明一个计数器变量(在这种情况下是i)来模拟相同的行为:

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

答案 2 :(得分:2)

你必须在while中定义一个真实的条件。

 while (x > 0)//true condition.

您希望多长时间打印一份打印声明。

 x--;//decrements the value by 1

答案 3 :(得分:1)

简单地:

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

阅读x的部分完全正确。

答案 4 :(得分:0)

您可以使用while循环,如下所示:

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

或者你也可以使用for循环;如果您知道循环在启动之前被调用的频率,这通常是最佳选择。