-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWhileLoop.java
More file actions
34 lines (31 loc) · 1.11 KB
/
WhileLoop.java
File metadata and controls
34 lines (31 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.Scanner;
/**
* 15. While loop Program in Java
*/
public class WhileLoop {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
int n;
System.out.println("Input an integer (Enter 0 to exit):");
// Loop until the user enters 0
while (true) {
// Validate if the input is an integer
if (scan.hasNextInt()) {
n = scan.nextInt();
if (n == 0) {
System.out.println("Exiting the loop. Goodbye!");
break;
}
System.out.println("You entered: " + n);
System.out.println("Input another integer (Enter 0 to exit):");
} else {
// Clear the invalid input
System.out.println("Invalid input! Please enter a valid integer.");
scan.next();
}
}
} catch (Exception e) {
System.out.println("An unexpected error occurred.");
}
}
}