0

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;
    }
  • 1
    Your program reads the first line (that constains "6") and the `indexData` doesn't start with `-1` so the original value of `vertexNames` is returned (and it is "temp") – KyreX May 22 '22 at 09:51
  • @KyreX I have the startsWith read as g - 1, is this what you mean? I see the problem of 6 causing it to return to temp but I'm not sure how to get around this – user17395771 May 22 '22 at 10:00
  • 1
    I don't understand what you do. The indices are sequential so you don't need to check anything. Also,, you are always reading the first line of the file each time the `indexFile()` is called. – KyreX May 22 '22 at 10:21
  • @KyreX I appreciate the advice and will try to fix it, if you can help me with what I need to change I'd really appreciate it as this is my first project with readers and this type of matrix – user17395771 May 22 '22 at 10:28
  • You should store the array in a `String[]` and use it. Now you are reading the entire file each time you call the method `getNames()`. – KyreX May 23 '22 at 17:05
  • I updated my answer with additional help for your new issue – KyreX May 23 '22 at 17:16

1 Answers1

0

You should read the entire file at once. If you want to keep the content for later, you can store it in a variable.

private String[] getNames(String fileName) throws IOException {
    String[] names = null;
    try(Scanner in = new Scanner(new File(fileName))) {
        int maxNames = Integer.parseInt(in.nextLine()); // Get the number of names to read
        names = new String[maxNames];
  
        int storedCount = 0;
        while(storedCount < maxNames && in.hasNextLine()) {
            String line = in.nextLine(); // Read a line
            if(!line.isEmpty()) { // If the line is not empty
                names[storedCount] = line.split(" ", 2)[1]; // Split the line in at most 2 tokens separated by a space and store the second
                storedCount++; // Increment the count of names already stored
            }
        }
    }
    return names;
}

With this method you can get the first N-titles of the file with N being the value of the first line. You will have to handle the possible exceptions.

QUESTION UPDATED

As I said in the comment of the question, you should store the array and then use as many times as you want. If you call the method getNames() N times, you are reading the same entire file N times (really inefficient)

To get each name followed by its number, you need to iterate both elements (names and numbers) at the same time

String[] names = getNames("input.txt"); // read file once
for(int i = 0; i < names.length; ++i) {
    strBuilder.append(names[i]).append(": ").append(adjMatrix[i]).append("\n"); // use it many
}
KyreX
  • 106
  • 5
  • Thanks for this I have tried to implement it and have run into errors that I can't make sense of. I am getting a syntax error after int maxNames.. saying it needs { instead of ; however if I change it it asks for the reverse, I have this issue lower down at return names and the } above it aswell. I have no other opened brackets or missing semi colons, any idea why this might be happening? – user17395771 May 23 '22 at 01:39
  • I missed a closing parenthesis at the `try` statement. It is fixed now. :) – KyreX May 23 '22 at 05:14
  • Hey thanks it works almost perfectly now however whjen printing instead of the words I get: [Ljava.lang.String;@27f674d. I'm sure this is a simple syntax error that I've made somewhere along the way do you have any idea what it could be? – user17395771 May 23 '22 at 06:19
  • Update, I fixed the above issue by using Arrays.toString() however it is now printing every single name in the array instead of appending the first one than moving to the next point in the matrix. I've edited the question with what the results now look like. I really appreciate your help so far – user17395771 May 23 '22 at 09:23
  • @user17395771, `java.lang.String;@27f674d` is printed because you tried to print the entire array and it hasn't the method `toString()` overrided. More details: https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array – KyreX May 23 '22 at 17:02