-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathForLoop.java
More file actions
40 lines (36 loc) · 1.34 KB
/
ForLoop.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
import java.util.Scanner;
/**
* 14. Simple For Loop Program in Java
*/
public class ForLoop {
public static void main(String[] args) {
try (Scanner scan = new Scanner(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();
}
int num1 = 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();
}
int num2 = scan.nextInt();
// Loop Logic
if (num2 > num1) {
System.out.println("Ascending Order:");
for (int i = num1; i <= num2; i++) {
System.out.println(i);
}
} else {
System.out.println("Descending Order:");
for (int i = num1; i >= num2; i--) {
System.out.println(i);
}
}
} catch (Exception e) {
System.out.println("Unexpected Error! Please try again. !!!");
}
}
}