Spaces:
Running
Running
File size: 2,356 Bytes
1614f5c | 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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | 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
|