- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathForLoop.java
More file actions
Latest commit
40 lines (36 loc) · 1.34 KB
/
Copy pathForLoop.java
File metadata and controls
40 lines (36 loc) · 1.34 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
35
36
37
38
39
40
importjava.util.Scanner;
/**
* 14. Simple For Loop Program in Java
*/
publicclassForLoop {
publicstaticvoidmain(String[] args) {
try (Scannerscan = newScanner(System.in)) {
System.out.println("Enter the Start number of Loop: ");
while (!scan.hasNextInt()) { // Ensure the input is a valid integer
System.out.println("Invalid input! Please enter a valid integer for Start number:");
scan.next();
}
intnum1 = scan.nextInt();
System.out.println("Enter the End number of Loop: ");
while (!scan.hasNextInt()) {
System.out.println("Invalid input! Please enter a valid integer for End number:");
scan.next();
}
intnum2 = scan.nextInt();
// Loop Logic
if (num2 > num1) {
System.out.println("Ascending Order:");
for (inti = num1; i <= num2; i++) {
System.out.println(i);
}
} else {
System.out.println("Descending Order:");
for (inti = num1; i >= num2; i--) {
System.out.println(i);
}
}
} catch (Exceptione) {
System.out.println("Unexpected Error! Please try again. !!!");
}
}
}