简体   繁体   English

无法从toString中的变量访问

[英]Can't access variable from toString in

I'm back with another question about my Dijkstra algorithm. 我回来了关于我的Dijkstra算法的另一个问题。 I fixed my previous question, but now I want to make a toString() method. 我解决了上一个问题,但现在我想制作一个toString()方法。

When I try to make it, the variables I use are unreachable from toString(), and I don't understand why. 当我尝试使用它时,我使用的变量无法通过toString()到达,而且我不明白为什么。

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. 您仅在public Graph(...)构造函数中声明了变量,而未在其余类的范围中声明。

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. 这是因为您在构造函数中声明并初始化了变量( graphFilestartVertexendVertex )。 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. 您也可以为其他人做同样的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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