I am trying to read a txt file and trying to save it in an array. following is the format of the txt file:
A B 5
A C 2
A D 4
.....
public class search {
public static void main(String[] args) throws ParseException {
try {
Scanner user_input = new Scanner(System.in); // for user input
System.out.println("Enter the file name: ");
String filename1 = user_input.next();
File file = new File(filename1);
search bd = new search();
Node[] nodes;
nodes = bd.getNodes(file);
bd.printNodes(nodes);
}
catch(Exception e) {
System.out.println("Error reading file " + e.getMessage());
}
}
public Node[] getNodes(File file) throws IOException {
FileReader bd = new FileReader(file);
BufferedReader bufferReader = new BufferedReader(bd);
String line;
ArrayList<Node>list = new ArrayList<Node>();
while ((line = bufferReader.readLine()) != null) {
String[] token = line.split(" "); // create string of tokens
list.add(new Node(token[0], token[1], Integer.parseInt(token[2])));
}
bufferReader.close();
return list.toArray(new Node[list.size()]); // converting list to array
}
public void printNodes(Node[] nodes) {
System.out.println("======================");
for(Node node : nodes) {
System.out.println(node);
}
System.out.println("======================");
}
Following is my Node class
class Node {
String leftchild;
String rightchild;
int cost;
public Node(){
}
public Node(String firstchild, String secondchild, int cost){
this.leftchild = firstchild;
this.rightchild = secondchild;
this.cost = cost;
}
public Node(String firstchild, String secondchild) {
this.leftchild = firstchild;
this.rightchild = secondchild;
}
public ArrayList<String> getChildren(){
ArrayList<String> childNodes = new ArrayList<String>();
if(this.leftchild != null)
{
childNodes.add(leftchild);
}
if(this.rightchild != null) {
childNodes.add(rightchild);
}
return childNodes;
}
public boolean removeChild(Node n){
return false;
}
@Override
public String toString() {
return leftchild +" "+ rightchild;
}
}
I have no compiling issues, but when I run my code, it is giving me error as
error reading file 1
Not sure why. I have tried to change my code in many ways but none of them worked. Could anyone please figure this out for me? Thanks
e.printStackTrace();in the catch blocks to display the full error message.Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1So I am guessing there is something problem with myprintNodesmethod?ArrayIndexOutOfBoundsExceptionmeans.