Reputation: 33
I have a text file containing the following content:
0 12
1 15
2 6
3 4
4 3
5 6
6 12
7 8
8 8
9 9
10 13
I want to read these integers from data.txt file and save the two columns into two different arrays in Java.
I am a beginner in Java, and thank you for your help.
Upvotes: 3
Views: 4189
Reputation: 420951
Unless you know the number of lines in the file in advance, I suggest you collect the numbers in two Lists
, such as ArrayList<Integer>
.
Something like this should do the trick:
List<Integer> l1 = new ArrayList<Integer>();
List<Integer> l2 = new ArrayList<Integer>();
Scanner s = new Scanner(new FileReader("filename.txt"));
while (s.hasNext()) {
l1.add(s.nextInt());
l2.add(s.nextInt());
}
s.close();
System.out.println(l1); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
System.out.println(l2); // [12, 15, 6, 4, 3, 6, 12, 8, 8, 9, 13]
If you really need the numbers in two int[]
arrays you can create the arrays afterwards (when the size is known).
Upvotes: 5