Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用扫描仪创建循环_Java_Loops - Fatal编程技术网

Java 使用扫描仪创建循环

Java 使用扫描仪创建循环,java,loops,Java,Loops,我正试图让它这样一个扫描器在用户输入的数字,然后打印hello world的多少次,用户已插补该数字使用一个while循环。我为x创建了一个扫描器,但是我很难找到如何正确执行循环 // import Scanner to take in number user imputs import java.util.Scanner; public class HelloWorld { public static void main(String[] args){ // crea

我正试图让它这样一个扫描器在用户输入的数字,然后打印hello world的多少次,用户已插补该数字使用一个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!");
        }
    }
}
简单地说:

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

零件读数
x
完全正确。

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

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

你必须在一段时间内定义一个真实的条件

 while (x > 0)//true condition.
您希望打印多少次打印对账单

 x--;//decrements the value by 1

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

Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
while (x > 0){
    // do something
    x--;
}
或者,您也可以使用
for
循环;如果您知道在循环开始之前调用循环的频率,那么这通常是最佳选择

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