I am a beginner in Java and I get this java.util.InputMismatchException for the code I have written it below. The error is:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Graph.main(Graph.java:103)
Once debugging it gives the error when it is going to execute int size = scan.nextInt(); line in main methor. I would appreciate if anyone can help me with this.
import java.io.*;
enter code here`import java.util.*;
import java.util.Random;
public class Graph {
private int maxSize;
private Vertex[] nodes; // array of nodes
private int[][] mat; // adjacency matrix
private int N;
public Graph(int maxSize) {
this.maxSize = maxSize;
nodes = new Vertex[maxSize];
mat = new int[maxSize][maxSize];
for(int i=0; i<maxSize;i++)
for(int j=0; j<maxSize;j++) mat[i][j]=0;
}
public void addVertex(int x, int y) {
if (N >= maxSize) {
System.out.println("Graph full");
return;}
nodes[N++] = new Vertex(x , y);
}
public void addEdge(int v1, int v2) {
mat[v1][v2] = 1;
mat[v2][v1] = 1;
}
//public static void main(String args[]) throws IOException
public void readFile() throws IOException
{
int xcoord;
int ycoord;
Scanner scan = new Scanner("vertex.txt");
int size = scan.nextInt();
int count = 0;
while (scan.hasNext() && count<size) {
scan.nextLine();
nodes[count].setX(scan.nextInt());
nodes[count].setY(scan.nextInt());
count++;
}
//Reads the edges file
Scanner scanEdge = new Scanner("edges.txt");
size = scanEdge.nextInt();
count = 0;
int weight;
//fill out the adjacency matrix
while (scanEdge.hasNext() && count<size) {
scanEdge.nextLine();
xcoord = scanEdge.nextInt(); // "from" node
ycoord = scanEdge.nextInt(); // "to" node
mat[xcoord][ycoord]=scanEdge.nextInt(); //weigth of the link
mat[ycoord][xcoord] = mat[xcoord][ycoord]; //Symmetric matrix
count++;
scanEdge.nextLine();
}
return;
}
public static void main(String args[]){
EasyIn easy = new EasyIn();
// Prints menu
System.out.println();
System.out.println("Welcome to Maze Genrator App");
System.out.println("=============================");
System.out.println("Menu");
System.out.println("====");
System.out.println("1- Read Graph from File");
System.out.println("2- Generate a Graph using a Grid with Random weigths");
System.out.println("3- Compute the Minimum Spanning Tree");
System.out.println("0- Exit");
int command = -1;
while (command != 0) {
if (command > 0) {String pause = easy.readString();} //Creates a pause
System.out.println();
command = easy.readInt(); //Takes command
switch (command){
case 1:
//Reads the vertices file.
Scanner scan = new Scanner("vertex.txt");
int size = scan.nextInt();
//Reads the vertices file
Graph myGraph = new Graph(size);
//String fileName = easy.readString();
try{
myGraph.readFile();
}
catch(IOException e){
e.printStackTrace();
}
System.out.println("List of edges + weigths");
break;
case 0: //Exit command
break;
default:
System.out.println("Selection Invalid!- Try Again");
}
}
System.out.println("Goodbye!");
}
}
public class Vertex {
// The vertex coordinates
private int x;//label e.g. A,B
private int y;//label e.g. A,B
public boolean visited; //Wether the node is visited or not
public Vertex (int x, int y) {
this.x = x;
this.y = y;
visited = false;
}
//display x,y coordinates of the graph
public void display() {
System.out.println(x + " " + y);
}
//set x coordinate
public void setX(int x){
this.x = x;
}
//set y coordinate
public void setY(int y){
this.y = y;
}
}
Once debugging it gives the error when it is going to execute "int
size = scan.nextInt();" line
It means that the next token isn't an integer.
You may want to call and check the return value of scan.hasNextInt(), to prevent this Exception.
Documentation says :
public class InputMismatchException extends NoSuchElementException
Thrown by a Scanner to indicate that the token retrieved does not
match the pattern for the expected type, or that the token is out of
range for the expected type.
new Scanner("vertex.txt")
This is a Scanner which reads the passed String (and not a file with that name). Since this String contains a filename and not a number it will fail.
What you're looking for is:
new Scanner(new File("vertex.txt"))
This one will first create a 'File' instance with the given filename and then pass that to the Scanner, so it will actually read the content of this file.
The same applies to your Scanner for the "edges.txt".
Related
I'm trying to read coordinates from a file into an array.
Every coordinate has an id, an x-value and a y-value.
The file is in the following format: id position.x position.y
Example:
292961234 1376.42 618.056
29535583 3525.73 530.522
256351971 836.003 3563.33
20992560 4179.74 3074.27
Note: There are 4 lines containing a total of 4 coordinates.
I created the class Node and its constructor expects (int id, double x, double y).
And this is the class NodeList which is supposed to have an array attribute that saves the Nodes:
package .....;
import java.io.File;
import java.util.Iterator;
import java.util.Locale;
import java.util.Scanner;
public class NodeList implements Iterable<Node> {
private Node[] nodes = getNodes();
#Override
public Iterator<Node> iterator() {
return null;
}
public Node[] getNodes() {
Node[] result;
File f;
Scanner scanner;
try {
f = new File("nodes.txt");
Scanner s = new Scanner(f);
int ctr = 0;
while (s.hasNextLine()) {
ctr++;
s.nextLine();
}
result = new Node[ctr];
}
catch (Exception e) {
return null;
}
try {
scanner = new Scanner(f);
}
catch (Exception e) {
return null;
}
Locale.setDefault(new Locale("C"));
for(int i = 0; i < result.length; i++) {
int id = scanner.nextInt();
double x = scanner.nextDouble();
double y = scanner.nextDouble();
result[i] = new Node(id,x,y);
}
return result;
}
public static void main(String[] args) {
NodeList nl = new NodeList();
}
}
The Node class:
package ...;
public class Node {
private int id;
private double x;
private double y;
public Node(int id, double x, double y){
this.id = id;
this.x = x;
this.y = y;
}
public int getId(){
return id;
}
public double getX(){
return x;
}
public double getY(){
return y;
}
}
When the method containing the shown code is called, I get the following
Exception:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at ......NodeList.getNodes(NodeList.java:40)
at ......NodeList.<init>(NodeList.java:9)
at ......NodeList.main(NodeList.java:47)
Process finished with exit code 1
Link to the file containing the nodes: https://pastebin.com/zhzp3DTi
It might be that it is using wrong locale.
I don't think "C" is a valid locale, it should be a language code.
You can try to use
scanner.useLocale(Locale.ROOT);
This is working on my machine:
public static void main(String[] args) {
// TODO code application logic here
String s = "292961234 1376.42 618.056\n" +
"29535583 3525.73 530.522\n" +
"256351971 836.003 3563.33\n" +
"20992560 4179.74 3074.27";
Scanner scanner = new Scanner(s);
scanner.useLocale(Locale.ROOT);
for(int i = 0; i < 4; i++) {
int id = scanner.nextInt();
double x = scanner.nextDouble();
double y = scanner.nextDouble();
System.out.println(id+" "+x+" "+y);
}
}
I want to take input from a file using the scanner class in Java. I want to read two coordinates of different cities from the file and then store them in an ArrayList of type City objects.
The input file format is as follows:
NAME : att48
COMMENT : 48 capitals of the US (Padberg/Rinaldi)
TYPE : TSP
DIMENSION : 5
EDGE_WEIGHT_TYPE : ATT
NODE_COORD_SECTION
1 6734 1453
2 2233 10
3 5530 1424
4 401 841
5 3082 1644
My sample code fragment is as follows: TourManager is a class containing an ArrayList of City objects. I haven't shown it here. City class contains every details (x,y coordinates) of a city.
try
{
Scanner in = new Scanner(new File("att48.tsp"));
String line = "";
int n;
//three comment lines
in.nextLine();
in.nextLine();
in.nextLine();
//get n
line = in.nextLine();
line = line.substring(11).trim();
n = Integer.parseInt(line);
City[] city= new City[n];
for (int i = 0; i < n; i++) {
city[i].x=0;
city[i].y=0;
}
//two comment lines
in.nextLine();
in.nextLine();
for (int i = 0; i < n; i++)
{
in.nextInt();
city[i].x = in.nextInt();
city[i].y = in.nextInt();
TourManager.addCity(city[i]);
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
But I am getting a NullPointerException in the line.
city[i].x = in.nextInt();
Although I have initialized it by 0 previously, the code throws the NullPointerException.
For clarity, City class is as follows:
public class City {
int x;
int y;
// Constructs a city at chosen x, y location
public City(int x, int y){
this.x = x;
this.y = y;
}
}
Is there a problem in the code?
You are getting error because after doing :
City[] city= new City[n];
You have not allocated memory to individual city[i] elements.
You have to do something like this, but for this you need to add a default constructor to your city class as you are assigning x and y afterwards:
for (i=0;i <n ;i++){
city[i]= new City();
}
Add the following constructor in your City class:
public City(){
}
or I would suggest you to revise your City class:
public class City {
private int x;
private int y;
// Constructs a city at chosen x, y location
public City(int x, int y) {
this.setX(x);
this.setY(y);
}
public City() {
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 7 years ago.
I want to be able to store and manage ordered pairs of the
form: (x, y). To solve this problem I created two classes: EuclideanSpace and Point. This is a homework assignment and so it is set up with these specific methods and the class EuclideanSpace and the inner class Point. I thought I had it almost figured out but when I run it it prints out '0' for the x and the y values after the first entry. For every entry after that it prints 'null'.
import java.util.Scanner;
public class EuclideanSpace {
Point point[];
Scanner scanner = new Scanner(System.in);
public EuclideanSpace() {
point = new Point[10];
}// End constructor
// Adds points to the array
public boolean addPoint(int x, int y) {
for (int i = 0; i < 10; i++) {
if (point[i] == null) {
point[i] = new Point();
}// End if
return true;
}// End for
return false;
}// End addPoint
// Prints a point in a given index in the point array
public void printPoint(int i) {
System.out.println(point[i]);
}
// Inner class
public static class Point {
private int x;
private int y;
public void Point(int x, int y) {
this.x = x;
this.y = y;
}// End Point method
public String toString() {
return "X = " + x + "Y = " + y;
}// End toString
}// End inner Class
}// End
Driver class:
import java.awt.Point;
import java.util.Scanner;
public class ICDriver {
static Scanner scanner = new Scanner(System.in);
// New object from the class EuclideanSpace
static EuclideanSpace es = new EuclideanSpace();
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println("Add point x coordinate? ");
int pointX = scanner.nextInt();
System.out.println("Add point y coordinate? ");
int pointY = scanner.nextInt();
es.addPoint(pointX, pointY);
es.printPoint(i);
} // End for
}// End main
}// End
// Correct your addPoint method
public boolean addPoint(int x, int y) {
for (int i = 0; i < 10; i++) {
if (point[i] == null) {
point[i] = new Point(x,y);
return true;
}// End if
}// End for
return false;
}// End addPoint
//Remove void from your constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
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.I have recently altered my Maze class as for it to run more efficiently but am being thrown errors and the data is parsing through to my DFS to be outputted. My Maze class is as follows:
import java.io.*;
import java.util.*;
public class Maze {
private 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));
}
/**
* 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);
}
}
And my DFS looks like so.
import java.io.File;
import java.io.FileNotFoundException;
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[] route;
private boolean[] visited;
// 2 main arguments - Maze File & user input
public DFS(Maze maze, int inputInt) {
int startNode = 0;
int goalNode = 1;
route = new int[maze.node];
visited = new boolean[maze.node];
//Takes user's input and runs desired function
if(inputInt == 1){
findOne(maze, startNode, goalNode);
}
else if (inputInt == 2){
findAll(maze, startNode, goalNode);
}
else {
System.out.println("input invalid. No Solution Returned");
}
}
//Put path to goal in the stack
public Stack<Integer> route(int toGoalNode) {
if (!visited[toGoalNode]) {
return null;
}
Stack<Integer> pathStack = new Stack<Integer>();
for (int routeGoalNode = toGoalNode; routeGoalNode != startNode; routeGoalNode = route[routeGoalNode]) {
pathStack.push(routeGoalNode);
}
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 findAll(Maze maze, int node, int goal) {
visited[node] = true;
if(node == goal) {
printPath(goal);
} else {
for (int con : maze.getadjList(node)) {
if (!visited[con]) {
route[con] = node;
findAll(maze, con, goal);
}
}
}
visited[node] = false;
}
//performs DFS and maintains visited marker giving only one path
private void findOne(Maze maze, int node, int goal) {
visited[node] = true;
for (int con : maze.getadjList(node)) {
if (!visited[con]) {
route[con] = node;
findOne(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 : route(toGoal)) {
if (t == toGoal) {
System.out.print(t);
} else {
System.out.print(t + " -> ");
}
}
System.out.println();
}
}
public static void main(String[] args) throws FileNotFoundException {
Scanner scanFile = new Scanner(System.in);
int goalNode = 1;
System.out.print("Enter maze file: ");
String file = scanFile.nextLine();
Maze maze = new Maze(new File(file));
Scanner scanInt = new Scanner(System.in);
System.out.print("Enter desired feedback (1 = one soultion, 2 = all): ");
int inputInt = scanInt.nextInt();
// maze.toString();
System.out.println(maze);
DFS dfs = new DFS(maze, inputInt);
dfs.printPath(goalNode);
}
}
I've been looking over it for a while and can't figure out exactly why the data is parsing and being used. Ive altered a few things here and there but have been thrown even more errors. They specifically say
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at DFS.findOne(DFS.java:90)
at DFS.<init>(DFS.java:22)
at DFS.main(DFS.java:127)
Referencing to the lines of code:
visited[node] = true;
findOne(maze, startNode, goalNode);
DFS dfs = new DFS(maze, inputInt);
Now essentially im lead to believe that there is no argument being passed, if someone could pin point the problem and lend a hand in helping me out it would be greatly appreciated. Thanks again
EDIT:: Old version of Maze class
import java.io.*;
import java.util.*;
public class Maze {
static Set<Integer> Nodes = new HashSet<Integer>();
List<Integer>[] conList;
int node; //declaring value for my nodes.
int con; // declaring a connection
//Constructor takes an int parameter to read through the list of corresponding nodes
Maze(int node) {
this.node = node;
this.con = 0;
conList = (List<Integer>[]) new List[node];
for (int index = 0; index < node; index++) {
conList[index] = new LinkedList<Integer>();
}
}
//Constructor that takes a String of the maze file
public Maze(String mazeFile) {
this(nodeSize(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 firstNode = scan.nextInt();
int secondNode = scan.nextInt();
addCon(firstNode, secondNode);
}
} catch (FileNotFoundException ex) {
System.out.println("File Not Found.");
}
}
/*Takes String parameter which is the name of the maze file.
* Method designed to return the the size of the set of nodes
*/
public static int nodeSize(String mazeFile) {
Scanner scanNodeSize;
try {
scanNodeSize = new Scanner(new File(mazeFile));
//while scan has more int's left repeat.
while (scanNodeSize.hasNextInt()) {
int firstNode = scanNodeSize.nextInt();
int secondNode = scanNodeSize.nextInt();
Nodes.add(firstNode);
Nodes.add(secondNode);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return Nodes.size();
}
//Method designed to connect the first and second nodes
private void addCon(int firstNode, int secondNode) {
con++;
conList[firstNode].add(secondNode);
conList[secondNode].add(firstNode);
}
//outputs the nodes and their connection's (#remove later?)
public void print() {
for (int n = 0; n < node; n++) {
System.out.print(n + " connected to ");
for (int w : conList[n]) {
System.out.print(w + " ");
}
System.out.println();
}
}
//method returns a list, enabling nodes to be easily accessible.
public Iterable<Integer> getconList(int nodes) {
return conList[nodes];
}
}
You are getting an index out of bounds exception at 0. This should lead you to believe that the array has not properly been initialized. You initialize the visited[] array with maze.node however nowhere in your code do we see where this node variable is located. You need to give a proper value to maze.node if you want this to even be runnable.
*EDIT - My above answer is no longer applicable now that we have your previous Maze class which explains why the code will not run.
There are so many things wrong with the code in its current state so I will try and give you some direction here:
Your new way of creating a Maze is to read from the file and connect the 2 points and store them in an Map. The issue with this is that you cannot just get the next element since you have to have the key to get the element. To fix this you should use a different data structure.
public DFS(Maze maze, int inputInt) {
int startNode = 0;
int goalNode = 1;
route = new int[maze.node]; //!!! maze.node isn't a thing anymore
visited = new boolean[maze.node]; //!!! maze.node isn't a thing anymore
You can see that you are trying to access maze.node which use to be a variable of Maze. It no longer is. You need to find a new way of getting a node from Maze. To do this you need to grab the node from your data structure in a different way:
public DFS(Maze maze, int inputInt) {
int startNode = 0;
int goalNode = 1;
route = new int[maze.adjList.getNode()];
visited = new boolean[maze.adjList.getNode()];
You have a lot of options for a different data structure for you adjacency list but something such as this:
http://theoryofprogramming.com/adjacency-list-in-java/
will give you a decent starting point.
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]);
}
}
}`}