-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExercise12_15.java
More file actions
43 lines (38 loc) · 1.28 KB
/
Exercise12_15.java
File metadata and controls
43 lines (38 loc) · 1.28 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
import java.io.*;
import java.util.*;
public class Exercise12_15 {
public static void main(String[] args) {
String filename = "Exercise 12_15.txt";
// Write
try (PrintWriter writer = new PrintWriter(filename)) {
Random random = new Random();
for (int i = 0; i < 100; i++) {
writer.print(random.nextInt(100) + " ");
}
} catch (FileNotFoundException e) {
System.out.println("Error: Unable to create file.");
e.printStackTrace();
}
// Read
ArrayList<Integer> numbers = new ArrayList<>();
try (Scanner scanner = new Scanner(new File(filename))) {
while (scanner.hasNextInt()) {
numbers.add(scanner.nextInt());
}
} catch (FileNotFoundException e) {
System.out.println("Error: Unable to read file.");
e.printStackTrace();
}
// Sort
Collections.sort(numbers);
// Display
System.out.println("Original numbers:");
for (int number : numbers) {
System.out.print(number + " ");
}
System.out.println("\n\nSorted numbers:");
for (int number : numbers) {
System.out.print(number + " ");
}
}
}