java.lang.NoSuchMethodError: Graph: method <init>()V not found - java

I'm getting a confusing error in eclipse but not on our main server from the command line linux account. All code is in the main src directory, in eclipse. Code compiles at command line but produces this error in Eclipse on my Mac OS X laptop:
Exception in thread "main" java.lang.NoSuchMethodError: Graph: method <init>()V not found
at Lab17.main(Lab17.java:11)
The code
Lab17.java
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
public class Lab17 {
// Lab17 first attempt at creating a graph
public static void main(String[] args) throws Exception {
Graph myGraph = new Graph();
URLConnection conn = null;
try {
URL url = new URL("http://csc.mendocino.edu/~jbergamini/222data/flights/flights");
conn = url.openConnection();
} catch (IOException e) {
System.out.println("Unable to open Flights file");
System.exit(1);
}
Scanner s = null;
try {
s = new Scanner(conn.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (s.hasNext()) {
String src = s.next();
String dst = s.next();
s.next();
double cost = s.nextDouble();
//System.out.println(src+" "+dst+" "+cost);
myGraph.addEdge(src, dst, cost);
}
System.out.println(myGraph.breadthFirst("Austin", "Washington"));
System.out.println(myGraph.depthFirst("LosAngeles", "Washington"));
System.out.println(myGraph.breadthFirst("LosAngeles", "Washington"));
System.out.println(myGraph.depthFirst("Washington", "LosAngeles"));
System.out.println(myGraph.breadthFirst("Washington", "LosAngeles"));
}
}
Graph.java
import java.util.LinkedList;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.TreeMap;
public class Graph {
private TreeMap<String, Vertex> vertexMap;
/** Creates a new, empty graph */
public Graph() {
// create vertexMap for Graph
vertexMap = new TreeMap<String, Vertex>();
}
/**
* Adds an edge
* #param src the source vertex
* #param dst the destination vertex
* #param cost the weight of the edge
*/
public void addEdge(String src, String dst, double cost) {
//System.out.println(src+" "+dst+" "+cost+" in Graph()");
// check to see if there is a src vertex
if(vertexMap.get(src) == null) {
// if src Vertex does not exist create Vertex for src
vertexMap.put(src, (new Vertex(src)));
//System.out.println(vertexMap.get(src).toString());
}
// check to see if there is a dst Vertex
if(vertexMap.get(dst) == null) {
// if dst Vertex does not exist create Vertex for dst
vertexMap.put(dst, (new Vertex(dst)));
//System.out.println(vertexMap.get(dst).toString());
}
// populate the dst and cost for Edge on the src Vertex vertexMap element
Vertex srdVertex = vertexMap.get(src);
Vertex dstVertex = vertexMap.get(dst);
Edge sEdge = new Edge(dstVertex, cost);
srdVertex.addEdge(sEdge);
}
/** Clears/empties the graph */
public void clear() {
vertexMap = new TreeMap<String,Vertex>();
}
/**
* Traverses, depth-first, from src to dst, and prints the vertex names in the order visited.
* #param src the source vertex
* #param dst the destination vertex
* #return whether a path exists from src to dst
*/
public boolean depthFirst(String src, String dst) {
System.out.println("Depth-first from "+src+" to "+dst);
for(Map.Entry<String,Vertex> entry: vertexMap.entrySet()) {
String key = entry.getKey();
Vertex thisVertex = entry.getValue();
System.out.println(key + " => " + thisVertex.toString());
}
return false;
}
/**
* Traverses, breadth-first, from src to dst, and prints the vertex names in the order visited
* #param src the source vertex
* #param dst the destination vertex
* #return whether a path exists from src to dst
*/
public boolean breadthFirst(String src, String dst) {
System.out.println("Breadth-first from "+src+" to "+dst);
// find starting vertex in vertexMap
Vertex start = vertexMap.get(src);
LinkedList<Vertex> vertexQue = new LinkedList<Vertex>();
LinkedList<Vertex> visitedV = new LinkedList<Vertex>();
// check it for null
if( start == null) {
throw new NoSuchElementException(" Start vertex not found");
}
// create a Queue for searching through vertex edges
//Queue<Vertex> q = new Queue<Vertex>();
vertexQue.add( start );
start.dest = 0;
boolean found = false;
while( !vertexQue.isEmpty() && !found) {
Vertex v = vertexQue.removeLast();
if( v.toString() == dst) {
// print queue
found = true;
}
else if(!visitedV.contains(v)){
// put all the adj vertex's into the queue
for( Edge e: v.getEdges() ) {
Vertex w = e.getDst();
vertexQue.add( w );
}
}
// add v to visitedV linked list
if(!visitedV.contains(v)){
visitedV.add(v);
}
}
System.out.print("[");
for(int i=0; i < visitedV.size(); i++) {
System.out.print(visitedV.get(i)+", ");
}
System.out.println("]");
/*forVertex> entry: vertexMap.entrySet()) {
String key = entry.getKey();
Vertex thisVertex = entry.getValue();
System.out.println(key + " => " + thisVertex.toString());
for(Edge e : thisVertex.getEdges() ){
System.out.print(e.toString());
}
System.out.println();
System.out.println("All Edges Evaluated");
}*/
return false;
}
}
Vertex.java
import java.util.Set;
import java.util.TreeSet;
public class Vertex {
private String name;
private TreeSet<Edge> adj;
public double dest;
/**
* Creates a new vertex
* #param name the name of the vertex
*/
public Vertex(String name) {
this.name = name;
adj = new TreeSet<Edge>();
}
public TreeSet<Edge> getEdges() {
return this.adj;
}
/**
* Returns the set of all edges starting from this vertex.
* Set shall be ordered with respect to the names of the destination vertices.
*/
public Set<Edge> allAdjacent() {
Set<Edge> vertexSet = adj;
return null;
}
public String toString() {
return name;
}
public void addEdge(Edge e) {
this.adj.add(e);
}
}
public class Edge implements Comparable<Edge> {
private Vertex dst;
private double cost;
/** Creates a new edge with an associated cost
* #param dst the destination vertex
* #param cost the weight of the edge
*/
public Edge(Vertex dst, double cost) {
this.dst = dst;
this.cost = cost;
}
public Vertex getDst() {
return dst;
}
#Override
public int compareTo(Edge o)
{
if(o == null)
return -1;
if(this == null)
return -1;
if( this.dst.toString().compareTo( ((Edge)o).dst.toString() ) == 0 )
return 0;
else if ( this.dst.toString().compareTo( ((Edge)o).dst.toString() ) < 0 )
return 1;
else
return -1;
}
public String toString() {
String theEdgeS = this.dst.toString()+" "+Double.toString(cost);
return theEdgeS;
}
}
Not sure why Eclipse environment is treating the code differently than the command-line environment is. The class's are a work in progress for a class. I'm only trying to solve what seems like an Eclipse bug.

It looks like the eclipse has an old version of Graph.class. You should try cleaning the project : See question Function of Project > Clean in Eclipse

Code compiles at command line but produces this error in Eclipse
Probable solutions :
1) Make sure the eclipse is using the same code as you use via command line.
2) Make a clean build inside eclipse because The case might be like it still referring the old class files regardless the thing that the source has been changed.

When you're running, Graph.class is not found in the classpath.

Related

How do I ask the user for input to remove any row from linked list ? (Using get and set methods)

I am trying to write a code that asks the user for input to remove any of the rows from my input file that I stored to my lined list index. Furthermore I will also have an error exception if the user went out of bounds or the row does not exist/not in the range.
I need to use a get method to get my index and return it and then use the remove method. At the end, I will output the file with the added changes and show it to the user.
I don't know if I my my get and remove methods are correct.
Hopefully someone can point me to the right direction !
here is my code thus far:
//class JOptionPane
import javax.swing.JOptionPane;
//class String Tokenizer
import java.util.StringTokenizer;
//class Scanner
import java.util.Scanner;
//class File
import java.io.File;
//class FileNotFoundException
import java.io.FileNotFoundException;
public class Testing19{
public static void main(String[]args){
//checks to see if there's an input file in the commandline
if(args.length != 1)
//displays an error if there's none
System.out.println("ERROR: NO INPUT FOUND");
else{
//create a new object file from the commandline
File file = new File(args[0]);
//creat a new scanner
Scanner data = null;
try{
//creates a link between the file and data
data = new Scanner(file);
}
catch(FileNotFoundException e){
//displays the error
System.out.println("ERROR: File not found");
}
//initialize a string for the
String output = new String();
//this will check for data inside the file
while(data.hasNextLine()){
//read the data per line in the file
String line = data.nextLine();
//initialize a string for name
String name;
//initialize a string for age
String scientificname;
//initialize a string for age
String color;
//initialize a string for age
String population;
//make a new scanner for token
Scanner tokenInput = new Scanner(line).useDelimiter(",");
//assign the first token as a string
name = tokenInput.next();
//assign the first token as a string
scientificname = tokenInput.next();
//assign the first token as a string
color = tokenInput.next();
//assign the second token as an string
population = tokenInput.next();
//reads the 2nd token as an integer
Integer population2 = Integer.parseInt(population);
//create a new object list from the class LinkedList
LinkedList list = new LinkedList();
//calls the add() method from the LinkedList class
list.add(name, scientificname, color, population2);
//assign the result in the output string
output = output + list;
}
//displays the output in the JOption pane
JOptionPane.showMessageDialog(null, output);
}
}//end of main
}//end of class
/****************************************
* Class LinkedList
*
*****************************************/
class LinkedListAldz{
//datafield
protected HawaiiNativeForestBirdsNode head = null;
protected Integer size = new Integer(0);
//add()method
public void add(String name2, String scientificname2, String color2, Integer population2){
if (head == null) {
//new PersonNode and store it on head if the list is empty
head = new HawaiiNativeForestBirdsNode(name2,scientificname2,color2,population2, null);
}
else {
//adds to the end of the list
HawaiiNativeForestBirdsNode previous = head;
HawaiiNativeForestBirdsNode current = head.getNext();
while (current != null) {
//next PersonNode
previous = current;
current = current.getNext();
}
//new PersonNode at the of the list.
HawaiiNativeForestBirdsNode birds = new HawaiiNativeForestBirdsNode(name2,scientificname2,color2,population2,null);
//point previous node
previous.setNext(birds);
}
size++;
}
/**
* Gets an item (address to an item) from any position in the list.
*
* #param position
* The position of an item in the list.
* #returns the address to the requested item
* #exception ListException
* if an item does not exist at that position
*/
public int get(Integer position) {
// check if empty list
if (head == null) {
System.out.println("Cannot get an item from an empty list!");
}
// if position is outside range, throw exception
if (position < 1 || position > size) {
System.out.println(position + " is outside list range!");
}
// Find node:
// counter to keep track of loops
Integer counter = new Integer(1);
// point to current node
HawaiiNativeForestBirdsNode current = head;
while (!counter.equals(position)) {
// BAD CODE: while(counter != position){
// goto next node for current pointer
current = current.getNext();
// add 1 to counter
counter++;
}
// return the data (item) stored by the node
return current.getData();
}
/**
* Removes an item at any position from the list.
*
* #param position
* The position of an item in the list.
* #exception ListException
* if an item does not exist at that position
*/
public void remove(Integer position) throws ListException {
// check if empty list
if (head == null) {
throw new ListException("cannot remove from empty list");
}
// if position is outside range, throw exception
if (position < 1 || position > size) {
throw new ListException(position + " is outside list range.");
}
// if at beginning of list
if (position.equals(1)) {
// remove 1st node
head = head.getNext();
}
// if not at beginning of list
else {
// Find node:
// point previous to 1st node
HawaiiNativeForestBirdsNode previous = head;
// point current to 2nd node
HawaiiNativeForestBirdsNode
current = head.getNext();
// loop position-2 number of times
for (int i = 2; i < position; i++) {
// goto next node for previous and current
previous = current;
current = current.getNext();
}
// Point the previous node to node after current node.
// This "skips" over one node, thus removing it!
previous.setNext(current.getNext());
}
// decrease size of list
size--;
}
//toString()method
public String toString() {
// instantiate empty string
String csvFormat = new String("");
// display position of each item to user
Integer position = new Integer(1);
// loop through all the nodes in linked list
for (HawaiiNativeForestBirdsNode current = head; current != null; current = current
.getNext()) {
// keep adding to end of string
csvFormat = csvFormat + current.toString() + "\n";
// add one to position for each loop
position++;
}
return csvFormat;
}
}//end of LinkedList
/****************************************
* Class PersonNode
* # param name for the name
* age for the age
* next for the next PersonNode
*****************************************/
class HawaiiNativeForestBirdsNode{
//data fields are set to private
private String name;
private String scientificname;
private String color;
private Integer population;
private HawaiiNativeForestBirdsNode next;
/********************************
* constructor method
* # param x is for the name
* y is for the age
* next2 is for the next
********************************/
public HawaiiNativeForestBirdsNode(String x, String y, String z, Integer b, HawaiiNativeForestBirdsNode next2) {
name = x;
scientificname = y;
color = z;
population = b;
next = next2;
}
/*******************************
* calls the toString method
* from the class String
* returns result
********************************/
public String toString(){
//initialize te format of the output
String result = name + " "+ scientificname + " " + color + " "+ population;
return result;
}
/*********************
* acessory method
* returns name
**********************/
public String getName(){
return name;
}
/*********************
* acessory method
* returns name
**********************/
public String getScientificname(){
return scientificname;
}
/*********************
* acessory method
* returns name
**********************/
public String getColor(){
return color;
}
/*********************
* acessory method
* returns age
**********************/
public Integer getPopulation(){
return population;
}
/*********************
* acessory method
* returns next
**********************/
public HawaiiNativeForestBirdsNode getNext(){
return next;
}
/*********************
* mutator method
* # param x is set name
**********************/
public void setName(String x){
name = x;
}
/*********************
* mutator method
* # param x is set name
**********************/
public void setScientificName(String y){
scientificname = y;
}
/*********************
* mutator method
* # param x is set name
**********************/
public void setColor(String z){
color = z;
}
/*********************
* mutator method
* # param y is set age
**********************/
public void setPopulation(Integer b){
population = b;
}
/**************************
* nutator method
* # param next2 is set next
***************************/
public void setNext(HawaiiNativeForestBirdsNode next2){
next = next2;
}
}//end of HawaiiNativeForestBirdsNode
The format of my input file is as follows:
1.akiapola'au,hemignathus munroi,yellow,800
2.akepa,loxops coccineus,red,9301
3.hawai'i creeper,oreomystis mana,yellow green,2501
4.i'iwi,vestiara coccinea,red green,30001
5.apapane,himatione sanguinea,white red,5001
6.hawai'i amakihi,hemignathus virens,yellow brown,3001
7.oma'o,myadestes obscurus,gray,170001
8.hawai'an hawk,buteo solitarius,white gray,1100
9.puaiohi,myadestes palmeri,brown,125
10.anianiau,magumma parva,light yellow,2000
I tried running it and I get an error:
Testing19.java:136: error: cannot find symbol
return current.getData();
^
symbol: method getData()
location: variable current of type HawaiiNativeForestBirdsNode
1 error
First, your class 'HawaiiNativeForestBirdsNode' does not contain a method 'getData ()'. That's why the exception is thrown. To get the users input you should use a BufferedReader instead:
import java.io.BufferedReader;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
- Luis

Creating a more concise traversal of a stack for DFS algorithm - Java [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am trying to get this code running as fast as possible when traversing through my stack of my DFS currently the input files are like so:
0 2
2 1
1 4
4 5
5 6
10 8
8 9
9 6
7 6
3 4
0 1
3 9
0 4
Where my Maze class will tie the numbers together and create a graph for me. After the graph is created my DFS class runs through traversing giving one or all solutions to the .txt file submitted. My DFS class looks like so:
import java.util.Scanner;
import java.util.Stack;
public class DFS {
//starting node, the route to the next node, has node been visited
private int startNode;
private int[] route2;
private boolean[] visited;
// 2 main arguments - Maze File & user input
public DFS(Maze maze, int inputInt) {
int startNode = 0;
int goal = 1;
route2 = new int[maze.node];
visited = new boolean[maze.node];
if(inputInt == 1){
startDFSone(maze, startNode, goal);
}
else if (inputInt == 2){
startDFSall(maze, startNode, goal);
}
else {
System.out.println("input invalid. No Solution Returned");
}
}
//Put path to goal in the stack
public Stack<Integer> route2(int toGoalNode) {
if (!visited[toGoalNode]) {
return null;
}
Stack<Integer> pathStack = new Stack<Integer>();
for (int route2GoalNode = toGoalNode; route2GoalNode != startNode; route2GoalNode = route2[route2GoalNode]) {
pathStack.push(route2GoalNode);
}
pathStack.push(startNode);
reverseStack(pathStack);
return pathStack;
}
//Reverse the stack
public void reverseStack(Stack<Integer> stackToBeReverse) {
if (stackToBeReverse.isEmpty()) {
return;
}
int bottom = popBottomStack(stackToBeReverse);
reverseStack(stackToBeReverse);
stackToBeReverse.push(bottom);
}
//Pop the bottom of the stack
private int popBottomStack(Stack<Integer> stackToBeReverse) {
int popTopStack = stackToBeReverse.pop();
if (stackToBeReverse.isEmpty()) {
return popTopStack;
} else {
int bottomStack = popBottomStack(stackToBeReverse);
stackToBeReverse.push(popTopStack);
return bottomStack;
}
}
//performs DFS and unsets visited to give the result of all paths
private void startDFSall(Maze maze, int node, int goal) {
visited[node] = true;
if(node == goal) {
printPath(goal);
} else {
for (int con : maze.getadjList(node)) {
if (!visited[con]) {
route2[con] = node;
startDFSall(maze, con, goal);
}
}
}
visited[node] = false;
}
//performs DFS and maintains visited marker giving only one path
private void startDFSone(Maze maze, int node, int goal) {
visited[node] = true;
for (int con : maze.getadjList(node)) {
if (!visited[con]) {
route2[con] = node;
startDFSone(maze, con, goal);
}
}
}
//Traverse the connections to the goal and print the path taken
public void printPath( int toGoal) {
int goalNode = 1;
if (visited[toGoal]) {
System.out.println("Completed Path: ");
for (int t : route2(toGoal)) {
if (t == toGoal) {
System.out.print(t);
} else {
System.out.print(t + " -> ");
}
}
System.out.println();
}
}
/**
*
* #param args
*/
public static void main(String[] args) {
Scanner scanFile = new Scanner(System.in);
int goalNode = 1;
System.out.print("Enter maze file: ");
String file = scanFile.nextLine();
Maze maze = new Maze(file);
Scanner scanInt = new Scanner(System.in);
System.out.print("Enter desired feedback (1 = one soultion, 2 = all): ");
int inputInt = scanInt.nextInt();
maze.print();
System.out.println();
DFS dfs = new DFS(maze, inputInt);
dfs.printPath(goalNode);
}
}
I am asking for some example or pointers to get my code (specifically the traversal of the stack) more concise so that when I implement my testing for completion time of the code I can minimize it as much as humanly possible.
I'll link my Maze class below if it might help. Thanks.
import java.io.*;
import java.util.*;
public class Maze {
final static Set<Integer> Nodes = new HashSet<Integer>();
List<Integer>[] adjList;
int node; //declaring value for my nodes.
int con; // declaring a connection
/**
* This constructors takes an integer parameter for reading node indexes in
* a list of adjacent nodes.
*
* #param node - integer parameter for passing the nodes value from the file
* and create a list of adjacent nodes.
*/
Maze(int node) {
this.node = node;
this.con = 0;
adjList = (List<Integer>[]) new List[node];
for (int index = 0; index < node; index++) {
adjList[index] = new LinkedList<Integer>();
}
}
/**
* The main constructor that takes a String for reading maze file.
*
* #param mazeFile
*/
public Maze(String mazeFile) {
this(getNodeSize(mazeFile));
Scanner scan;
try {
//Creates a scanner for reading the file and loops through linking the nodes to their connections.
scan = new Scanner(new File(mazeFile));
while (scan.hasNextInt()) {
int node1 = scan.nextInt();
int node2 = scan.nextInt();
addCon(node1, node2);
}
} catch (FileNotFoundException ex) {
System.out.println("File Not Found.");
}
}
/**
* This method returns a size of the set of nodes by taking a String
* parameter which the name of the maze file.
*
* #param mazeFile - String parameter for reading maze file for scanning the
* size of the nodes.
* #return - returns an integer value for the size of the set of nodes.
*/
public static int getNodeSize(String mazeFile) {
Scanner scanNodeSize;
try {
scanNodeSize = new Scanner(new File(mazeFile));
while (scanNodeSize.hasNextInt()) {
int node1 = scanNodeSize.nextInt();
int node2 = scanNodeSize.nextInt();
Nodes.add(node1);
Nodes.add(node2);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return Nodes.size();
}
/**
* This method adds an con by adding two different nodes in array of list
* called adjacency list.
*
* #param node1 - first node.
* #param node2 - next node.
*/
private void addCon(int node1, int node2) {
con++; //Increase con by one whenever this addcon method is called.
adjList[node1].add(node2);
adjList[node2].add(node1);
}
/**
* Print the nodes and its cons by looping through the adjacency list.
*/
public void print() {
for (int n = 0; n < node; n++) {
System.out.print(n + " connected to ");
for (int w : adjList[n]) {
System.out.print(w + " ");
}
System.out.println();
}
}
/**
* This method returns a list of nodes to allow objects to be the target for
* "for-each" statement.
*
* #param nodes - an Integer parameter for getting the number of nodes in a
* list.
* #return - returns a list of nodes.
*/
public Iterable<Integer> getadjList(int nodes) {
return adjList[nodes];
}
/**
* Unit testing To test if it reads the file.
*
* #param args
*/
public static void main(String[] args) {
System.out.print("Enter File: ");
Scanner scanFile = new Scanner(System.in);
String file = scanFile.nextLine();
Maze M = new Maze(file);
M.print();
}
}
Also any general input would be fantastic.

Returning a value from a method and using it in another class - Java

Currently in my Maze class I have two methods
public Set<Integer> getNode(int node) {
return Collections.unmodifiableSet(adjList.get(node));
}
and
public int getNumberOfNodes() {
return adjList.size();
}
I am trying to pull through my current node into my DFS class but I seem to be missing something. Currently with my DFS class I have this.
private int[] route;
private boolean[] visited;
public DFS(Maze maze, int input) {
int startNode = 0;
int goalNode = 1;
route = new int[maze.getadjList(node)]; << errors here
visited = new boolean[maze.adjList.getNode()]; << errors here
//Takes user's input and runs desired function
if(input == 1){
findOne(maze, startNode, goalNode);
}
else if (input == 2){
findAll(maze, startNode, goalNode);
}
else {
System.out.println("input invalid. No Solution Returned");
}
}
Feel free to ask me anything if I can help. Thanks
Full Maze class if needed:
import java.io.*;
import java.util.*;
public class Maze {
final Map<Integer, Set<Integer>> adjList = new HashMap<>();
/**
* The main constructor that takes a String for reading maze file.
*
* #param file
*/
public Maze(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
while (scan.hasNextInt()) {
int node1 = scan.nextInt();
int node2 = scan.nextInt();
this.connect(node1, node2);
this.connect(node2, node1);
}
}
}
/**
* Makes a unidirectional connection from node1 to node2.
*/
private void connect(int node1, int node2) {
if (!this.adjList.containsKey(node1)) {
this.adjList.put(node1, new HashSet<Integer>());
}
this.adjList.get(node1).add(node2);
}
/**
* Returns a human-readable description of the adjacency lists.
*/
public String toString() {
StringBuilder s = new StringBuilder();
for (Map.Entry<Integer, Set<Integer>> adj : this.adjList.entrySet()) {
int from = adj.getKey();
Set<Integer> to = adj.getValue();
s.append(from).append(" connected to ").append(to).append('\n');
}
return s.toString();
}
/**
* Returns the set of nodes connected to a particular node.
*
* #param node - the node whose neighbors should be fetched
*/
public Iterable<Integer> getadjList(int node) {
return Collections.unmodifiableSet(adjList.get(node));
}
public Set<Integer> getNode(int node) {
return Collections.unmodifiableSet(adjList.get(node));
}
public int getNumberOfNodes() {
return adjList.size();
}
/**
* Demonstration of file reading.
*/
public static void main(String[] args) throws FileNotFoundException {
System.err.print("Enter File: ");
Scanner scanFile = new Scanner(System.in);
String file = scanFile.nextLine();
Maze m = new Maze(new File(file));
System.out.println(m);
}
}
These statements look like they are trying to create a new int array and a new boolean array:
route = new int[maze.getadjList(node)]; << errors here
visited = new boolean[maze.adjList.getNode()]; << errors here
but to create an array the parameter between the square brackets must be an int.
Its value gives the size of the array.
The functions you are calling do not return ints, hence you get errors.
As #Ian Mc stated in the comments the problem was resolved by first initiating the arrays using.
route = new int[maze.getNumberOfNodes()]
visited = new boolean[ maze.getNumberOfNodes()]

Reading from text file to array of object in java

I am working on Dijkstra algorithm. The program that I have read the data from a text file. the program works fine if I input the relation in the program but it does not work when I try to read the input from text file.
the input to the program in the program itself is as following:
private static final Graph.Edge[] Arr = {
new Graph.Edge("a", "b", 1),
new Graph.Edge("a", "c", 1),
new Graph.Edge("a", "f", 1),
new Graph.Edge("b", "c", 1),
new Graph.Edge("b", "d", 1),
new Graph.Edge("c", "d", 1),
new Graph.Edge("c", "f", 1),
new Graph.Edge("d", "e", 1),
new Graph.Edge("e", "f", 1),
};
what I have tried to read from text file to be instead of this input is as following:
first, I count the number of the line to be the size of the array:
public static int count;
public static void countLines(String file) throws IOException
{
LineNumberReader lnr = new LineNumberReader(new FileReader(new File(file)));
lnr.skip(Long.MAX_VALUE);
Dijkstra.count=lnr.getLineNumber() + 1;
lnr.close();
}
The function that will do the reading from the text file and saving the data to the array is as following:
public static Graph.Edge[] readTextFile(String fileName) {
String line = null;
Graph.Edge[] Gr=new Graph.Edge[Dijkstra.count-1];
try {
FileReader fileReader = new FileReader("txt2.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
int i=0;
while ((line = bufferedReader.readLine()) != null) {
String[] tokens = line.split("\\t+");
String s = tokens[0];
String e = tokens[2];
Gr[i] =new Graph.Edge(s, e, 1);
i=i+1;
}
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
}
return Gr;
}
these functions and the main are within some class called Dijkstra. the whole code is as following:
package shortestPath;
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Dijkstra {
/*private static final Graph.Edge[] Arr = {
new Graph.Edge("a", "b", 1),
new Graph.Edge("a", "c", 1),
new Graph.Edge("a", "f", 1),
new Graph.Edge("b", "c", 1),
new Graph.Edge("b", "d", 1),
new Graph.Edge("c", "d", 1),
new Graph.Edge("c", "f", 1),
new Graph.Edge("d", "e", 1),
new Graph.Edge("e", "f", 1),
};*/
public static int count;
//public static Graph.Edge[] GRAPH = new Graph.Edge[count] ;
public static void countLines(String file) throws IOException
{
LineNumberReader lnr = new LineNumberReader(new FileReader(new File(file)));
lnr.skip(Long.MAX_VALUE);
Dijkstra.count=lnr.getLineNumber() + 1; //Add 1 because line index starts at 0
// Finally, the LineNumberReader object should be closed to prevent resource leak
lnr.close();
//return Dijkstra.count;
}
public static Graph.Edge[] readTextFile(String fileName) {
String line = null;
Graph.Edge[] Gr=new Graph.Edge[Dijkstra.count-1];
try {
FileReader fileReader = new FileReader("txt2.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
int i=0;
while ((line = bufferedReader.readLine()) != null) {
String[] tokens = line.split("\\t+");
String s = tokens[0];
String e = tokens[2];
Gr[i] =new Graph.Edge(s, e, 1);
i=i+1;
}
// Always close files.
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
}
//return Dijkstra.GRAPH;
return Gr;
}
private static final String START = "12";
private static final String END = "18";
public static void main(String[] args) throws IOException {
countLines("hsa00072.txt");
Graph.Edge[] GRAPH=readTextFile("hsa00072.txt");
Graph g = new Graph(GRAPH);
g.dijkstra(START);
g.printPath(END);
//g.printAllPaths();
}
}
class Graph {
private final Map<String, Vertex> graph; // mapping of vertex names to Vertex objects, built from a set of Edges
/** One edge of the graph (only used by Graph constructor) */
public static class Edge {
public final String v1, v2;
public final int dist;
public Edge(String v1, String v2, int dist) {
this.v1 = v1;
this.v2 = v2;
this.dist = dist;
}
}
/** One vertex of the graph, complete with mappings to neighbouring vertices */
public static class Vertex implements Comparable<Vertex> {
public final String name;
public int dist = Integer.MAX_VALUE; // MAX_VALUE assumed to be infinity
public Vertex previous = null;
public final Map<Vertex, Integer> neighbours = new HashMap<>();
public Vertex(String name) {
this.name = name;
}
private void printPath() {
if (this == this.previous) {
System.out.printf("%s", this.name);
} else if (this.previous == null) {
System.out.printf("%s(unreached)", this.name);
} else {
this.previous.printPath();
System.out.printf(" -> %s(%d)", this.name, this.dist);
}
}
public int compareTo(Vertex other) {
return Integer.compare(dist, other.dist);
}
}
/** Builds a graph from a set of edges */
public Graph(Edge[] edges) {
graph = new HashMap<>(edges.length);
//one pass to find all vertices
for (Edge e : edges) {
if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));
if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));
}
//another pass to set neighbouring vertices
for (Edge e : edges) {
graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);
//graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected graph
}
}
/** Runs dijkstra using a specified source vertex */
public void dijkstra(String startName) {
if (!graph.containsKey(startName)) {
System.err.printf("Graph doesn't contain start vertex \"%s\"\n", startName);
return;
}
final Vertex source = graph.get(startName);
NavigableSet<Vertex> q = new TreeSet<>();
// set-up vertices
for (Vertex v : graph.values()) {
v.previous = v == source ? source : null;
v.dist = v == source ? 0 : Integer.MAX_VALUE;
q.add(v);
}
dijkstra(q);
}
/** Implementation of dijkstra's algorithm using a binary heap. */
private void dijkstra(final NavigableSet<Vertex> q) {
Vertex u, v;
while (!q.isEmpty()) {
u = q.pollFirst(); // vertex with shortest distance (first iteration will return source)
if (u.dist == Integer.MAX_VALUE) break; // we can ignore u (and any other remaining vertices) since they are unreachable
//look at distances to each neighbour
for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {
v = a.getKey(); //the neighbour in this iteration
final int alternateDist = u.dist + a.getValue();
if (alternateDist < v.dist) { // shorter path to neighbour found
q.remove(v);
v.dist = alternateDist;
v.previous = u;
q.add(v);
}
}
}
}
/** Prints a path from the source to the specified vertex */
public void printPath(String endName) {
if (!graph.containsKey(endName)) {
System.err.printf("Graph doesn't contain end vertex \"%s\"\n", endName);
return;
}
graph.get(endName).printPath();
System.out.println();
}
/** Prints the path from the source to every vertex (output order is not guaranteed) */
public void printAllPaths() {
for (Vertex v : graph.values()) {
v.printPath();
System.out.println();
}
}
}
The text file is as following:
12 ECrel 15
15 ECrel 18
11 ECrel 12
12 ECrel 14
11 ECrel 14
11 ECrel 18
14 maplink 17
the problem is whenever I want to find the path like from node 12 to node 18 it will say 18(unreached) even if there is a path but it will not return the path. in case of the input in the program it works fine and return the path. the problem is only appears when trying to read from the text file.
There is something very strange going on here. I'll babble along as I work through it.
I get randomly different results (sometimes your program works as you wanted, sometimes not). Often they are different depending on whether I am running in debug mode or not.
So . . . it's time to look for a source of randomness. Clearly you're not using randomness directly/intentionally. So we should look somewhere else for the randomness.
I think I see two potential sources of randomness.
When you're traversing the NavigableSet, it's doing a lot of comparing equal values at first. That's necessary and makes sense, but it might lead to randomness, since it doesn't have to pick one particular order of how to present the elements to you.
You also use Maps in your algorithm, and there are no promises about what order their entrySets come back in.
My guess is that your algorithm is actually sensitive to the order in which things are presented to it. I haven't dug in enough to know which bits might be the problem, but maybe this section goes two different directions if two equally good routes are presented to it in different orders:
if (alternateDist < v.dist) { // shorter path to neighbour found
q.remove(v);
v.dist = alternateDist;
v.previous = u;
q.add(v);
}
and possibly one of those routes never leads to the destination you're looking for.
I would actually suggest getting out bits of paper and writing the vertices on them, and shuffling them whenever your algorithm calls for an iterator over map EntrySets.
My suspicion for why this works when reading from the source and fails when reading from code: different random seeds. That's it. It's technically prone to the same failure in both cases, it just happens to pick a working path in one JVM scenario and a non-working path in the other JVM scenario.
Sorry this is kind of fuzzy and really long. Maybe it will help.

File input for Dijkstra's algorithm

I am having trouble figuring out how to read an input file with java. The file has the following format:
u1 v1 w1
u2 v2 w2
...
um vm wm
-1
source
Each 3-tuple denotes an edge, which is specified by its source-vertex, its destination-vertex, and its weight (example: newyork boston 30). The description of the graph is terminated by a “flag”, the integer -1. A string follows this flag; this string is the name of the source vertex for the Dijkstra shortest-path algorithm. That is, you are to determine and print out the shortest path from this source vertex to every other vertex in the graph.
Here is my current work.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.PriorityQueue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
class Vertex implements Comparable<Vertex> {
public final String name;
public Edge[] adjacencies;
public double minDistance = Double.POSITIVE_INFINITY;
public Vertex previous;
public Vertex(String argName) {
name = argName;
}
public String toString() {
return name;
}
public int compareTo(Vertex other) {
return Double.compare(minDistance, other.minDistance);
}
}
class Edge {
public final Vertex target;
public final double weight;
public Edge(Vertex argTarget, double argWeight) {
target = argTarget;
weight = argWeight;
}
}
public class Dijkstra {
public static void computePaths(Vertex source) {
source.minDistance = 0.;
PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
vertexQueue.add(source);
while (!vertexQueue.isEmpty()) {
Vertex u = vertexQueue.poll();
// Visit each edge exiting u
for (Edge e : u.adjacencies) {
Vertex v = e.target;
double weight = e.weight;
double distanceThroughU = u.minDistance + weight;
if (distanceThroughU < v.minDistance) {
vertexQueue.remove(v);
v.minDistance = distanceThroughU;
v.previous = u;
vertexQueue.add(v);
}
}
}
}
public static ArrayList<Vertex> getShortestPathTo(Vertex target) {
ArrayList<Vertex> path = new ArrayList<Vertex>();
for (Vertex vertex = target; vertex != null; vertex = vertex.previous)
path.add(vertex);
Collections.reverse(path);
return path;
}
public String[] readFile(String fileName) throws FileNotFoundException {
Scanner input = new Scanner(new File(fileName));
String line = "";
while (input.hasNext()) {
line = line.concat(input.nextLine());
}
String[] graph = line.split("");
return graph;
}
public static void main(String[] args) throws FileNotFoundException {
final String TEST = "/TestInput.txt";
Scanner input = new Scanner(new File(TEST));
String line = "";
while (input.hasNext()) {
line = line.concat(input.nextLine());
}
String[] graph = line.split(" ");
for (int i = 0; i < graph.length; i++) {
System.out.println(graph[i]);
}
Vertex[] verts = new Vertex[graph.length];
Edge[] edges = new Edge[graph.length];
Vertex v1 = new Vertex("");
Vertex v2 = new Vertex("");
Vertex source = new Vertex("");
int count = 0;
outerloop: for (int i = 0; i < (graph.length); i++) {
if (graph[i].equals("-1")) {
// do algorithm initialization here w/ source
}
if (i == 0) {
verts[i] = new Vertex(graph[i]);
count++;
} else {
innerloop: for (int j = count; j >= 0; j--) {
if (i / 3 == 0) {
if (graph[i].equals(verts[j].toString())) {
break innerloop;
} else if (j == 0) {
verts[count] = new Vertex(graph[i]);
v1 = verts[count];
count++;
}
}
if (i / 3 == 1) {
if (graph[i].equals(verts[j])) {
break innerloop;
} else if (j == 0) {
verts[count] = new Vertex(graph[i]);
v2 = verts[count];
count++;
}
}
if (i / 3 == 2) {
}
}
}
}
for (int i = 0; i < verts.length; i++) {
System.out.println(verts[i]);
}
}
}
So my only problem is how to get from the given .txt file format to a graph. Any suggestions are welcome.
Use a Scanner to parse the file data. For each tuple, if the source vertex hasn't been created, create it, otherwise find it in the pre-existing graph -- create a search function. Do the same for the target vertex. Next, create an edge with a weight equal to the third token in the tuple, and add the target vertex to the edge. Finally, add the edge to the adjacency list of the source vertex.
For the previously mentioned search function, you can implement something that can search through each vertex of the graph starting from any vertex. Recursion will be necessary.
public static Vertex search(Vertex src, String name);
A simpler solution is to keep a list of all the vertices you create as your constructing the graph and search through that.
public static Vertex search(List<Vertex> vertices, String name);
When your done constructing the graph and you have the name of the vertex where Dijkstra's algorithm will begin, you can use the search function to get a reference to the vertex.
Dijkstra.computePath(search(vertices, startVertexName));
And, that's it. Here's an example of how to parse your file data:
List<Vertex> vertices = new ArrayList<Vertex>();
String src =
"Pittsburgh Philadelphia 323 "+
"Pittsburgh Ohio 125 "+
"Ohio Philadelphia 400 "+
"-1 Ohio";
//new Scanner(new File(fileName));
Scanner scnr = new Scanner(src);
String src, target;
int weight;
while(scnr.hasNext())
{
src = scnr.next();
if(src.equals("-1"))
break;
else {
target = scnr.next();
weight = scnr.nextInt();
}
//call search(), implement logic in addToGraph()
addVertexToGraph(src, target, weight, vertices);
}
String startVertexName = scnr.next();
scnr.close();
Note that Scanner.next returns the next token separated by white space (the default delimiter), so your file data must be formatted that way.
Here's a shot:
/**
* Read the file using provided filename, construct vertices etc.
*
* #param fileName name of the file to read.
* #return true if everything is OK
* #throws FileNotFoundException if file is not found or not readable
*/
public boolean readFile(final String fileName) throws FileNotFoundException {
final Scanner input = new Scanner(new File(fileName));
boolean result = false;
while (input.hasNext()) {
final String line = line = input.nextLine();
if ("-1".equals(line)) {
// end of data
if (input.hasNext()) {
final String nameOfTheSource = input.next();
// TODO: do something with nameOfTheSource
result = true;
} else {
// bad input format: there should be something after -1
}
} else {
final String Scanner vert = new Scanner(line);
try {
final String sourceName = vert.next();
final String targetName = vert.next();
final int weight = vert.nextInt(); // assuming int for weight
// TODO: create Vertices and Edge here
} catch (final NoSuchElementException ex) {
// bad input format for "line"!
}
}
}
return result;
}
Not tested.
{import Stack.Dijkstra;
{import java.io.File;
{import java.io.FileNotFoundException;
{import java.util.Scanner;
{public class App {
{public static void main(String[] args) throws {FileNotFoundException {
{Vertex v1 = new Vertex("A");
{Vertex v2 = new Vertex("B");
{Vertex v3 = new Vertex("C");
{`v1.addNeighbour(new Edge(1, v1, v2));
{`v1.addNeighbour(new Edge(10, v1, v2));
{`v2.addNeighbour(new Edge(1, v2, v3));
{`Dijkstra dijkstra = new Dijkstra();
{`dijkstra.computePath(v1);
{`System.out.println(dijkstra.getShortestPathTo(v3));
{`final String test = "X:\\neon3\\eclipse\\TestInput.txt";
{`Scanner input = new Scanner(new File(test));
{`String line = "";
{`while (input.hasNext()) {
{`line = line.concat(input.nextLine());
}
{`String[] graph = line.split(" ");
{`for (int i = 0; i < graph.length; i++) {
{`System.out.println(graph[i]);
}
}
}`}

Categories

Resources