Reputation: 63
I'm trying read a set of numbers from a file and then isolate the lines in between the first line (which lets us know how many lines will need to be worked on, in this case, 5) and the seventh line (mind you that this is just an example, the range of the lines will is subject to change) so that I can populate a list in the format of (0 1 98, 0 2 5, ...,4 3 15). Right now my code manages to get (0 1 98, 0 2 5, 0 3 16, 0 4 16) added into the list but not the rest. I'm not sure what I've done wrong. Any help would be much appreciated.
Example input:
5
0 1 98 2 5 3 16 4 16
1 0 13 2 47 3 3 4 40
2 0 71 1 51 3 43 4 30
3 0 20 1 94 4 46
4 0 1 1 10 2 28 3 15
2
2 3
2
0 1
public static void t() {
List<String> L = new ArrayList();
try {
BufferedReader f = new BufferedReader(new FileReader("graph.txt"));
String s = f.readLine();
int nodes = Integer.parseInt(s);
int c = -1;
int c1 = 2;
int c2 = 3;
for (int i = 0; i < nodes; i++) {
s = f.readLine();
String z [] = s.split(" ");
String start = z[0];
for (int j = 0; j < z.length; j++) {
int t = c+c1;
int t2 = c+c2;
if (t >= z.length) {
break;
}
String des = z[t];
if (t2 >= z.length+1) {
break;
}
String weight = z[t2];
L.add(start + " " + des + " " + weight);
c1+=2;
c2+=2;
}
}
for (int i = 0; i < L.size(); i++) {
System.out.println(L.get(i));
}
} catch (Exception ex) {
System.out.println(ex);
}
}
Upvotes: 1
Views: 131
Reputation: 2558
You just need to reset your C
variables within the outer loop.
for (int i = 0; i < nodes; i++) {
s = f.readLine();
String z [] = s.split(" ");
String start = z[0];
// Declare the variables here, otherwise code is the same
int c = -1;
int c1 = 2;
int c2 = 3;
for (int j = 0; j < z.length; j++) {
int t = c+c1;
int t2 = c+c2;
if (t >= z.length) {
break;
}
String des = z[t];
if (t2 >= z.length+1) {
break;
}
String weight = z[t2];
L.add(start + " " + des + " " + weight);
c1+=2;
c2+=2;
}
}
Upvotes: 1