I'm unable to print for the getLines method, am I doing something wrong here? It doesnt give me any errors when I run the program but when I try to print the getlines method, it gives me errors.
it gives me this erros when i try to print the getlines method.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at dijkstra.Fileprocess.getLines(Fileprocess.java:37) at dijkstra.Fileprocess.main(Fileprocess.java:70)
public class Fileprocess {
public static Scanner Reader(String FileName){
//Pass a File Name to this method, then will return Scanner for reading data from that file
try {
return new Scanner(new File(FileName));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
System.exit(1);
return null;
}
}
static ArrayList<Edge> getLines(ArrayList<Vertex> PointCollection) {
Scanner Input = Reader(Vertex.graph);
ArrayList<Edge> result = new ArrayList<Edge>();
while(Input.hasNext()){
String line = Input.nextLine();
String[] arr = line.split(" ");
result.add(new Edge(Integer.parseInt(arr[0]), //index
getPointbyIndex(PointCollection,Integer.parseInt(arr[1])), //start
getPointbyIndex(PointCollection,Integer.parseInt(arr[2])), //end
Integer.parseInt(arr[3]))); //cost
}
Input.close();
return result;
}
static ArrayList<Vertex> getPoints() {
Scanner Input = Reader(Vertex.airports);
ArrayList<Vertex> result = new ArrayList<Vertex>();
while(Input.hasNext()){
String line = Input.nextLine();
result.add(new Vertex(line));
}
Input.close();
return result;
}
static Vertex getPointbyIndex(ArrayList<Vertex>PointCollection, int Index){
for(Vertex p:PointCollection){
if(p.getIndex() == Index){
return p;
}
}
return null;
}
public static void main(String[] args){
System.out.println(getPoints());
System.out.println(getLines(null));
}
}
this is the file for the input text file(index,start,end,cost)
1 1 2 2
2 1 3 1
3 1 6 3
4 1 7 3
5 2 1 2
6 2 3 1
7 2 4 1
8 2 5 2
9 2 6 2
10 3 1 1
11 3 2 1
12 3 4 1
class Edge {
public Vertex start;
public Vertex end;
public double cost;
public int Index;
// public final Vertex target;
// public final int weight;
public Edge(double cost, Vertex end, Vertex start, int Index){
this.start = start;
this.end = end;
this.cost = cost;
this.Index = Index;
}
public String toString(){
String result = "";
if(this.start != null && this.end != null){
result = this.Index +","+this.start.Index+","+this.end.Index +","+this.cost;
}
return result;
}
}
Maybe your file contains an empty or incompatible line?
you can fix the error using:
String[] arr = line.split(" ");
if (arr.length > 3) {
result.add(new Edge(Integer.parseInt(arr[0]), //index
getPointbyIndex(PointCollection,Integer.parseInt(arr[1])), //start
getPointbyIndex(PointCollection,Integer.parseInt(arr[2])), //end
Integer.parseInt(arr[3]))); //cost
}
}
Related
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 developing a maze system but not graphically maze system. The maze is actually referred as undirected graph I think because they don't direct to each other. The maze looks like this from a text file:
11 3
2 3
0 3
1 4
5 4
5 7
6 7
7 8
8 9
9 10
0 5
I don't know if I did was right to represent this in graph. If you check my code, it seems to be right, isn't it?
import java.io.*;
import java.util.Scanner;
class Arc {
public int nodeNo;
public Arc next;
public Arc(int nodeNo, Arc next) {
this.nodeNo = nodeNo;
this.next = next;
}
public String toString(){
return "" + nodeNo;
}
}
class Node {
int index;
Arc adjList;
Node(int index, Arc adjList) {
this.index = index;
this.adjList = adjList;
}
public String toString() {
return "" + index;
}
}
public class Maze {
Node[] stack;
private Scanner scan;
private static Scanner scan2;
public Maze(String mazeFile) throws FileNotFoundException {
scan = new Scanner(new File(mazeFile));
stack = new Node[12];
for (int n = 0; n < stack.length; n++) {
stack[n] = new Node(n, null);
}
while (scan.hasNext()) {
int v1 = indexForNode(scan.next());
int v2 = indexForNode(scan.next());
stack[v1].adjList = new Arc(v2, stack[v1].adjList);
stack[v2].adjList = new Arc(v1, stack[v2].adjList);
}
}
int indexForNode(String index) {
for (int n = 0; n < stack.length; n++) {
if (stack[n].index == Integer.parseInt(index)) {
return n;
}
}
return -1;
}
public void print(){
System.out.println();
for(int n = 0; n < stack.length; n++){
System.out.print(stack[n]);
for(Arc arc = stack[n].adjList; arc != null; arc = arc.next){
System.out.print(" --> " + stack[arc.nodeNo].index);
}
System.out.println("\n");
}
}
public static void main(String[] args) throws FileNotFoundException {
scan2 = new Scanner(System.in);
System.out.print("Enter maze file name: ");
String file = scan2.nextLine();
Maze maze = new Maze(file);
maze.print();
}
}
In general, I would say no: this is not a good approach. A basic graph, where the edges don't have weights, is implemented as a series of nodes with a Many ↔ Many relationship.
So basically your Node would look like this:
public class Node {
private List<Node> out;
}
See this question for more information.
I have an input like:
Apple: 0 1
Apple: 4 5
Pear: 0 10
Pear: 11 13
Apple: 5 10
Apple: 2 4
And I'm looking for rows, where the fruits are the same and the first value equals to another row's second vale. So I'm looking for rows like: Apple: 4 5 Apple: 2 4 and I will also need Apple: 4 5 Apple: 5 10
On the otherhand, I don't want to search the whole data. I mean I don't want to search for Apple in Pears.
Should I use HashMap? or HashSet? or something else?
Thanks for replies.
Give this a try... It utilizes a HashMap of Lists
public static void main(String[] args) {
List<String> inputs = new ArrayList<>();
inputs.add("Apple: 0 1");
inputs.add("Apple: 4 5");
inputs.add("Pear: 0 10");
inputs.add("Pear: 11 13");
inputs.add("Apple: 5 10");
inputs.add("Apple: 2 4");
Map<String, List<Fruit>> fruits = new HashMap<>();
for (String input : inputs) {
String[] inputPieces = input.split(" ");
String name = inputPieces[0].replace(":", "");
int first = Integer.parseInt(inputPieces[1]);
int second = Integer.parseInt(inputPieces[2]);
if (!fruits.containsKey(name)) {
fruits.put(name, new ArrayList<Fruit>());
}
fruits.get(name).add(new Fruit(name, first, second));
}
for (String key : fruits.keySet()) {
System.out.println(key + ": " + findDuplicates(fruits.get(key)));
}
}
private static List<Fruit> findDuplicates(List<Fruit> fruits) {
List<Fruit> results = new ArrayList<>();
for (int i = 0; i < fruits.size(); i++) {
for (int j = 0; j < fruits.size(); j++) {
if (j == i) {
continue;
}
if ((fruits.get(i).first == fruits.get(j).second) ||
(fruits.get(j).first == fruits.get(i).second)) {
if (!results.contains(fruits.get(i))){
results.add(fruits.get(i));
}
}
}
}
return results;
}
public static class Fruit {
private String name;
private int first;
private int second;
public Fruit(String name, int first, int second) {
this.name = name;
this.first = first;
this.second = second;
}
#Override
public String toString() {
return String.format("%s: %d %d", name, first, second);
}
}
Results:
My code is getting a runtime error in UVA online judge, but it is running fine in my compiler.I don't know exactly where the problem is. So help me. Below is my code.
class reverseAdd {
public static int checkPalingdromMarker(long [] a1,long [] a2){
int c=0;
for(int q=0;q<a2.length/2;q++){
if(a1[q]!=a2[q]){
break;
}
else c++;
}
if(c==(a2.length/2))
{
return 1;
}
return 0;
}
public static void checkPalingdrom(long [] a1,long [] a2){
int c=0;
for(int q=0;q<a2.length/2;q++){
if(a1[q]!=a2[q]){
System.out.println("Not Palingdrom");
break;
}
else c++;
}
if(c==(a2.length/2))
{
System.out.println("Palingdrom found");
}
}
public static long [] reverseNumberDigits(long numToDigits){
String string = Long.toString(numToDigits);
long[] digits = new long[string.length()];
/*
for(int y = 0; y<string.length(); ++y){
digits[y] = Long.parseLong(string.substring(y, y+1));
}
*/
int reverse=0,i=string.length();
while( numToDigits != 0 )
{
reverse = reverse * 10;
digits[i-1] = reverse + numToDigits%10;
numToDigits = numToDigits/10;
i=i-1;
}
return digits;
}
public static long reverseNumber(long numberToReverse){
long reverse = 0;
while( numberToReverse != 0 )
{
reverse = reverse * 10;
reverse = reverse + numberToReverse%10;
numberToReverse = numberToReverse/10;
}
return reverse;
}
public static long [] readNumsFromCommandLine() {
Scanner s = new Scanner(System.in);
int count = s.nextInt();
s.nextLine(); // throw away the newline.
long [] numbers = new long[count];
for(int i = 0; i < count; i++){
if(s.hasNextLong()){
numbers[i] = s.nextLong();
s.nextLine();
}
}
return numbers;
}
public static void main(String[] args) {
long[] numbers = readNumsFromCommandLine();
int inputLength=numbers.length;
for(int f=0;f<inputLength;f++){
int countAddition=1;
long a=numbers[f]+reverseNumber(numbers[f]);
for(int x=0;x<1000;x++){
System.out.println(a);
if(checkPalingdromMarker(reverseNumberDigits(reverseNumber(a)), reverseNumberDigits(a))==0){
countAddition++;
a=a+reverseNumber(a);
}
else{
System.out.println(countAddition+" "+reverseNumber(a));
break;
}
}
}
}
}
UVa Online Judge has specific requirements for submitted code in order for it to correctly compile. There are 2 mistakes in your code preventing compilation.
Change the first line of your code:
class reverseAdd {
to
import java.util.*;
class Main {
Note: I ran your code and it will result in a "Wrong Answer" result in UVa.
For sample input:
3
24 1
4358 754
305 794
The expected output is:
34
1998
1
Your code's (incorrect) output is:
4358 754
305 794
66
1 66
12892
42713
74437
147884
636625
1163261
2786872
7 2786872
808
1 808
I have to make a program that reads each word a file and makes an index of which lines the word occurs on in alphabetical order.
for example, if the file had:
a white white dog
crowded around the valley
the output should be:
a
around: 2
crowded: 2
dog: 1
the: 2
valley: 1
white: 1, 1
When my file contains:
one fish two fish blue fish green fish
cow fish milk fish dog fish red fish
can you find a little lamb
can you find a white calf
THE OUTPUT IS WRONG!: (NOT IN ALPHA ORDER)
a: 3 4
calf: 4
find: 3 4 4
lamb: 3
little: 3
white: 4
you: 3 4
blue: 1
can: 3
cow: 2
dog: 2
green: 1 1 2 2 2 2
milk: 2
red: 2
two: 1 1 1
fish: 1
one: 1
Here is my code::
INDEXMAKER MASTER CLASS
import java.io.*;
import java.util.*;
public class IndexMaker {
private ArrayList<Word> words;
private String fileName;
private String writeFileName;
public IndexMaker(String fileName, String writeFileName) {
this.fileName = fileName;
this.writeFileName = writeFileName;
words = new ArrayList<Word>();
}
public void makeIndex() {
try {
File file = new File(fileName);
Scanner lineScanner = new Scanner(file);
int lineNum = 0;
while (lineScanner.hasNext()) {
lineNum++;
Scanner wordScanner = new Scanner(lineScanner.nextLine());
while (wordScanner.hasNext()) {
String word = wordScanner.next().toLowerCase();
if (!words.contains(new Word(word))) {
insertInto(word, findPosition(word), lineNum);
} else {
addLineNum(word, lineNum);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void displayIndex() {
try {
//FileWriter fileWriter = new FileWriter(new File(writeFileName));
//BufferedWriter writer = new BufferedWriter(fileWriter);
for (Word word : words)
System.out.println(word.getWord() + ": " + word.getLineNums());
} catch (Exception e) {
}
}
private int findPosition(String word) {
for (int i = 0; i < words.size(); i++) {
if (word.compareTo(words.get(i).getWord()) <= 0)
return i;
}
return 0;
}
private void insertInto(String word, int pos, int lineNum) {
words.add(pos, new Word(word, String.valueOf(lineNum)));
}
private void addLineNum(String word, int lineNum) {
int pos = findPosition(word);
words.get(pos).addLineNum(lineNum);
}
}
WORD CLASS
public class Word {
private String word;
private String lineNums;
public Word(String word, String lineNum) {
this.word = word;
this.lineNums = lineNum;
}
public Word(String word) {
this.word = word;
this.lineNums = "";
}
public String getWord() {
return word;
}
public String getLineNums() {
return lineNums;
}
public void addLineNum(int num) {
lineNums += " " + num;
}
#Override
public boolean equals(Object w) {
if (((Word)w).getWord().equals(word))
return true;
else
return false;
}
}
CLIENT
public class Client {
public static void main(String[] args) {
IndexMaker indexMaker = new IndexMaker("readme.txt", "readme.txt");
indexMaker.makeIndex();
indexMaker.displayIndex();
}
}
any help would be appreciated, thanks.
I can't find your definition of compareTo. It seems this would be the key part of your program?
Properly implement your compareTo and confirm it works properly by printing the results of comparisons using System.out.println
Doing your own comparison is "ok" in that it will work if you do it properly. The other thing you could do would be to implement Comparable and then you can get Java to sort a list of words for you.