-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadIntegers.java
More file actions
34 lines (31 loc) · 1 KB
/
ReadIntegers.java
File metadata and controls
34 lines (31 loc) · 1 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.*;
import java.io.*;
public class ReadIntegers {
public static int[] readIntegers() {
Scanner in = new Scanner(System.in);
//System.out.print("Input number of elements: ");
int n = in.nextInt();
int[] numbers = new int[n];
//System.out.print("Input " + Integer.toString(n) + " elements: ");
for (int i = 0; i < n && in.hasNextInt(); i++) {
numbers[i] = in.nextInt();
}
return numbers;
}
public static int[] readIntegersFromFile(String fileName) {
Scanner in;
try {
File file = new File(fileName);
in = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("File: " + fileName + " not found.");
return new int[0];
}
int n = in.nextInt();
int[] numbers = new int[n];
for (int i = 0; i < n && in.hasNextInt(); i++) {
numbers[i] = in.nextInt();
}
return numbers;
}
}