Sunny
Sunny

Reputation: 11

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

Upvotes: 0

Views: 128

Answers (4)

Lakshraj
Lakshraj

Reputation: 291

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

You are not incrementing 'i' in while loop. 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.

Upvotes: 0

Oppa
Oppa

Reputation: 154

With a while loop, it has a condition. In your case, i < number. The while loop will run "While" this condition is true. 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. Usually, you increment at the end of the while loop, so after your println call.

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

Upvotes: 1

Keshav Pradeep Ramanath
Keshav Pradeep Ramanath

Reputation: 1697

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!

Upvotes: 3

Mahendra
Mahendra

Reputation: 8924

while(i < number) {

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

you need to increment i by 1 one each iteration.

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

Upvotes: 1

Related Questions