KaiquanMah's picture
Create 17b. Read numbers from a file
1614f5c verified
raw
history blame
2.36 kB
Numbers are stored in the file numbers.csv.
One line contains several numbers separated by commas.
The file could look like this:
1,2,1,2,3
4,3,2,3,2,4,2
1,2,3
Write the method
ArrayList<Integer> allValues()
which reads the numbers from the file, and stores them in a list.
Finally, the list is returned.
Example method call:
public static void main(String[] args){
ArrayList<Integer> list = allValues();
System.out.println(list);
}
Example output:
[1, 2, 1, 2, 3, 4, 3, 2, 3, 2, 4, 2, 1, 2, 3]
==================================
import java.util.Random;
import java.util.ArrayList;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;*/
public class Test {
public static void main(String[] args){
final Random random = new Random();
System.out.println("File:");
for (String s : input) {
System.out.println("" + s);
}
ArrayList<String> list = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
System.out.println("Testing the file's numbers...");
ArrayList<Integer> numbers = allValues();
System.out.println("All values:");
for (int value : numbers) {
System.out.println(value);
}
}
//ADD
public static ArrayList<Integer> allValues() {
ArrayList<Integer> list = new ArrayList<>();
try {
Scanner reader = new Scanner(new File("numbers.csv"));
// read each line
while (reader.hasNextLine()) {
String line = reader.nextLine();
// split line into array of Integer strings
String[] values = line.split(",");
for (String value : values) {
list.add(Integer.valueOf(value));
}
}
}
catch (FileNotFoundException e) {
System.out.println("Error: numbers.csv file not found");
}
return list;
}
}
File:
431,668,669,425,27,491,241
751,718,167,454,665,251,958
218,887,235,954,948,947,763
122,306,137,719,905,921,349
Testing the file's numbers...
All values:
431
668
669
425
27
491
241
751
718
167
454
665
251
958
218
887
235
954
948
947
763
122
306
137
719
905
921
349