Is there a way to read a file into Java line by line, with each line having a series of integers (different amount of integers per line). For example:
2 5
1 3 4 5
2 4 8
2 3 5 7 8
etc.
I will be reading the line number and numbers in each row into a 2-dimensional array.
Right now, here is the code I have:
int i=1, j;
try{
Scanner sc=new Scanner(new File("mapinput.txt"));
while(sc.hasNext()){
String line=sc.nextLine();
while(line!=null){
j=sc.nextInt();
Adj[i][j]=1;
}
i++;
}
} catch(Exception e){System.err.println(e);};
The problem with this code, I see, is that it's reading the integers one line after String line; I want it to read the numbers in that very line. Is there a way to read the numbers from a String?
Update:
I decided to go with the StringTokenizer route; however, when it gets to the last line of my file, I receive a java.util.NoSuchElementException: No line found error. Here is my updated code:
try{
Scanner sc=new Scanner(new File("mapinput.txt"));
String line=sc.nextLine();
st=new StringTokenizer(line, " ");
do{
while(st.hasMoreTokens()){
j=Integer.parseInt(st.nextToken());
Adj[i][j]=1;
}
line=sc.nextLine();
st=new StringTokenizer(line, " ");
i++;
}while(st.hasMoreTokens());
} catch(Exception e){System.err.println(e);};