-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjavalab18.java
More file actions
59 lines (52 loc) · 1.9 KB
/
Copy pathjavalab18.java
File metadata and controls
59 lines (52 loc) · 1.9 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.io.*;
import java.util.*;
class ArmstrongNumCounter {
public static boolean isArmstrongNum(String st) {
try {
int num = Integer.parseInt(st);
int temp = num, sum = 0;
int digits = st.length();
while (temp != 0) {
int rem = temp % 10;
sum += Math.pow(rem, digits);
temp /= 10;
}
return sum == num;
} catch (NumberFormatException e) {
return false;
}
}
public static List<Integer> countArmstrongNums(String filename) throws IOException {
List<Integer> armstrongNumbers = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = br.readLine()) != null) {
String[] words = line.split(" ");
for (String word : words) {
if (!word.isEmpty() && isArmstrongNum(word)) {
armstrongNumbers.add(Integer.parseInt(word));
}
}
}
} catch (Exception e) {
System.out.println("Error: " + e.toString());
}
return armstrongNumbers;
}
}
public class javalab18 {
public static void main(String[] args) {
String file = "C:\\Users\\Asus\\OneDrive\\Documents\\myNumFile.txt";
try {
ArmstrongNumCounter ob = new ArmstrongNumCounter();
List<Integer> armstrongNums = ob.countArmstrongNums(file);
System.out.println("Number of Armstrong numbers: " + armstrongNums.size());
System.out.print("Armstrong Numbers: ");
for (int num : armstrongNums) {
System.out.print(num + " ");
}
} catch (IOException e) {
System.out.println("IOException occurred: " + e.toString());
}
}
}