UPDATE: With the help of @KyreX the code now correctly reads the file and prints the array of names as vertexes HOWEVER it is now printing the entire array of names as vertexes instead of appending one at each time resulting in this:
Gromit: Gwendolyn: Le-Spiderman: Wallace: Batman: Superman: 0 1 0 1 0 0
Gromit: Gwendolyn: Le-Spiderman: Wallace: Batman: Superman: 1 0 0 1 0 1
Gromit: Gwendolyn: Le-Spiderman: Wallace: Batman: Superman: 0 0 0 0 1 0
Gromit: Gwendolyn: Le-Spiderman: Wallace: Batman: Superman: 1 1 0 0 0 0
Gromit: Gwendolyn: Le-Spiderman: Wallace: Batman: Superman: 0 0 1 0 0 0
Gromit: Gwendolyn: Le-Spiderman: Wallace: Batman: Superman: 0 1 0 0 0 0
The code resulting in this print looks like this:
public String toString() {
StringBuilder s = new StringBuilder();
for (int i = 0; i < numVertices; i++) {
try {
int q = 0;
while (q < getNames("index.txt").length) {
s.append(getNames("index.txt")[q] + ": ");
q++;
}
} catch (IOException e) {
e.printStackTrace();
}
for (boolean j : adjMatrix[i]) {
s.append((j ? 1 : 0) + " ");
}
s.append("\n");
}
return s.toString();
}
I am trying to create an adjacency matrix in java from a .txt file, the program is supposed to read the following file:
6
0 Gromit
1 Gwendolyn
2 Le-Spiderman
3 Wallace
4 Batman
5 Superman
It is then supposed to use this information to assign the vertexes of the matrix using the number preceding the name. E.g. 0 Gromit is position 0 etc. The 6 above the pairs is the number of pairs in the file, this must remain. The problem I have is that when I run my code instead of printing the names as the vertexes it prints the word "temp: " followed by the edges assigned to that position. This is my code:
public String toString() {
StringBuilder s = new StringBuilder();
for (int i = 0; i < numVertices; i++) {
String vertexName = "temp";
s.append(indexFile(vertexName, i) + ": ");
for (boolean j : adjMatrix[i]) {
s.append((j ? 1 : 0) + " ");
}
s.append("\n");
}
return s.toString();
}
// reading index.txt
public String indexFile(String vertexNames, int g) {
try {
File indexObj = new File("index.txt");
Scanner indexReader = new Scanner(indexObj);
String indexData = indexReader.nextLine();
if (indexData.startsWith(Integer.toString(g - 1)) == true) {
String[] posAndName = indexData.split(" ");
vertexNames = posAndName[1];
System.out.print("it is " + posAndName[1]);
}
g++;
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
e.printStackTrace();
}
return vertexNames;
}