Java while loop
Created By: chatGPT
While loops in Java are used to repeat a block of code as long as a specified condition is true. It's essential to ensure that the condition will eventually evaluate to false; otherwise, the loop will run indefinitely, causing a runtime error. Here's a simple example to illustrate how a while loop works.
int count = 0;
while (count < 5) {
System.out.println("Count is: " + count);
count++;
}
In this example, the loop starts with count initialized to 0. The condition checks if count is less than 5. If true, it prints the current value of count and then increments count by 1. This process repeats until count becomes 5, at which point the loop terminates.
public class WhileLoopExample {
public static void main(String[] args) {
int count = 0;
while (count < 5) {
System.out.println("Count is: " + count);
count++;
}
}
}
It's also possible to use a while loop for other tasks, such as reading from an input until a specific condition is met. Here’s an example that reads numbers from the user until they enter a negative number.
import java.util.Scanner;
public class WhileLoopInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = 0;
while (number >= 0) {
System.out.print("Enter a number (-1 to exit): ");
number = scanner.nextInt();
if (number >= 0) {
System.out.println("You entered: " + number);
}
}
System.out.println("Exiting...");
scanner.close();
}
}