简体   繁体   English

无限的while循环。 如何修复n次?

[英]Infinite while loop. How do I fix it for n number of time?

the statement keeps on repeating. 该语句不断重复。

int number;
int i = 0; 

System.out.print("Enter a number: "); 
number = input.nextInt();

while(i < number)    
    System.out.println("Welcome to Java!");

Code

Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int number = reader.nextInt();
int i = 0;
do {
    System.out.println("Welcome to Java!");
     i++;
}
while (i < number);

Output 输出量

Enter a number: 
5
Welcome to Java!
Welcome to Java!
Welcome to Java!
Welcome to Java!
Welcome to Java!
while(i < number) {

  System.out.println("Welcome to Java!");
  i++;
}

you need to increment i by 1 one each iteration. 您需要将i每次迭代增加1。

do {
   System.out.println("Welcome to Java!");
   i++;;
}while(i < number);

With a while loop, it has a condition. 使用while循环时,它具有条件。 In your case, i < number. 在您的情况下,我<数字。 The while loop will run "While" this condition is true. while循环将在“条件为真”的情况下运行。 So, to make this condition not true, i needs to be more than "number". 因此,要使此条件不成立,我需要大于“数字”。 To make i greater than the number, you need to increment it. 要使我大于数字,您需要增加它。 You can increment it with i++ which will add one to i, each time its called. 您可以用i++递增它,每次调用i时都会向i加1。 Usually, you increment at the end of the while loop, so after your println call. 通常,您在while循环结束时递增,因此在println调用之后递增。

while(i < number){    
System.out.println("Welcome to Java!");
i++;
}
while(i < number)    
System.out.println("Welcome to Java!");

You are not incrementing 'i' in while loop. 您不会在while循环中增加“ i”。 That's why the loop is going in infinite loop. 这就是循环进入无限循环的原因。

while(i < number) {   
        System.out.println("Welcome to Java!");
    i++; // increment of i
}

That will work fine. 那会很好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM