简体   繁体   中英

Can't access variable from toString in

I'm back with another question about my Dijkstra algorithm. I fixed my previous question, but now I want to make a toString() method.

When I try to make it, the variables I use are unreachable from toString(), and I don't understand why.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;

public class Graph
{

ArrayList<Vertex> vertexObjects = new ArrayList<Vertex>();
ArrayList<Edge> edgeObjects = new ArrayList<Edge>();
ArrayList<Vertex> visitedObjects = new ArrayList<Vertex>();
ArrayList<Vertex> unvisitedObjects = new ArrayList<Vertex>();
ArrayList<Edge> tempEdge = new ArrayList<Edge>();
int numVertices = 0;

public void readFile(String textfile)
{
    try {
        Scanner s = new Scanner(new File(textfile));
        String sameVertex = "";

        while (s.hasNext()) {
            String preVertex = s.next();
            String postVertex = s.next();
            String distance = s.next();

            Edge temp = new Edge(preVertex, postVertex, distance);
            edgeObjects.add(temp);

            if (!(preVertex.equals(sameVertex)))
            {
                Vertex herp = new Vertex(preVertex, Double.POSITIVE_INFINITY, false, null);
                vertexObjects.add(herp);
                sameVertex = preVertex;
                numVertices++;
            }
        }
    } catch (FileNotFoundException e) {
        System.out.println("I can't find that file!");
    }
}

public void dijkstra(String startVertex, String endVertex)
{


    // Change the distance of the startVertex to 0 and all others to infinity.
    for (int i = (numVertices-1); i >= 0; i--)
    {
        if (vertexObjects.get(i).vertexName.equals(startVertex))
        {
            vertexObjects.get(i).distance = 0;
        } else {
            vertexObjects.get(i).distance = Double.POSITIVE_INFINITY;
        }
    }

    //Set the node with lowest distance value to Current Status
    unvisitedObjects = vertexObjects;
    double smallDistance = Double.POSITIVE_INFINITY;
    while(unvisitedObjects.size() != 0) {
        //set current node to vertex with shortest distance
        String currentNode = "";
        for (int j = (unvisitedObjects.size()-1); j >= 0; j--) {
            if (unvisitedObjects.get(j).distance <= smallDistance) {
                smallDistance = unvisitedObjects.get(j).distance;
                currentNode = unvisitedObjects.get(j).vertexName;
            }
        }
        //remove the smallest distance having node from the unvisited array
        //and place into visited array.
        for (int g = (unvisitedObjects.size()-1); g >= 0; g--) {
            if (unvisitedObjects.get(g).vertexName.equals(currentNode))
            {
                visitedObjects.add(unvisitedObjects.get(g));
                unvisitedObjects.remove(g);
            }
        }
        //for all the nodes that are adjacent to the current node, update their
        //distance values if they are larger than the weight plus previous distances.
        for (int w = (edgeObjects.size()-1); w >= 0; w--) {
            if (edgeObjects.get(w).startVertex == currentNode) {
                tempEdge.add(edgeObjects.get(w));
            }
            for (int t = (tempEdge.size()-1); t >=0; t--) {
                for (int p = (vertexObjects.size()-1); p >= 0; p--) {
                    if (tempEdge.get(t).endVertex == vertexObjects.get(p).vertexName)
                    {
                        if ((Double.parseDouble(tempEdge.get(t).edgeWeight) + smallDistance) < vertexObjects.get(p).distance) {
                            vertexObjects.get(p).distance = (Double.parseDouble(tempEdge.get(t).edgeWeight) + smallDistance);
                        }
                    }
                }
            }   
        }
    }

    String smallDString = Double.toString(smallDistance);


}

public Graph(String textfile, String startingVertex, String endingVertex) {
    String graphFile = textfile;
    String startVertex = startingVertex;
    String endVertex = endingVertex;
}

public String toString() {
    return ("The shortest path from "+startVertex+" to "+endVertex+" is "+smallDistance+".");
}
}

You need to make them field in your class. Not just local variables. For example in your constructor you can do:

private String graphFile;  // declare variable to store value

public Graph(String textfile, String startingVertex, String endingVertex) {
    graphFile = textfile;  // assign value in constructor
    ...

You can't access them because they are initialized within a function. You need to declare them as global variables.

ArrayList<Vertex> vertexObjects = new ArrayList<Vertex>();
ArrayList<Edge> edgeObjects = new ArrayList<Edge>();
ArrayList<Vertex> visitedObjects = new ArrayList<Vertex>();
ArrayList<Vertex> unvisitedObjects = new ArrayList<Vertex>();
ArrayList<Edge> tempEdge = new ArrayList<Edge>();
int numVertices = 0;
String startVertex, smallDistance, endVertex = "";

that might be the problem.

You've only declared the variables in the public Graph(...) constructor, not in the scope for the rest of the class.

You need to declare them in the class body (normally near the top) for the methods to have access to them.

This is because you declared and initialized the variables ( graphFile , startVertex , endVertex ,) inside of your constructor. This means that they are only visible/usable inside the constructor . You need to declare them as class variables, then you can initialize them in the constructor. For example

public class Graph {
    String graphFile;

    public Graph(String textfile) {
        this.graphFile = textfile;
    }
}

You can do the same for the others as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM