-1

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);};
user3326317
  • 11
  • 1
  • 5
  • Once you read in a line, split that line on the ' ' character. – Eric J. May 08 '14 at 00:52
  • The problem is calling sc.nextLine() advances scanner by a line (hence skipping a line) and then you are calling sc.nextInt() which reads int next to that position. – OOO May 08 '14 at 01:02

2 Answers2

0

once you read a line you can do following

String[] ar=line.split(" ");

and play with String array based on your requirement

dev2d
  • 4,245
  • 3
  • 31
  • 54
0

Look into the #StringTokenizer class in Java Libraries.

You can easily iterate through the file and pull the integers delimited by spaces. It handles the two + digit integers well.

To answer your question directly, there is a way to get numbers from a String.

Look into

Integer.parseInt(String s);  

This returns an integer from the String.

Documentation is here

String s1 = "15 ";
String s2 = "03";
int answer = Integer.parseInt(s1.trim()) + Integer.parseInt(s2.trim());
System.out.println(answer);

This prints out:

18
Garret
  • 1,137
  • 9
  • 17
  • 1
    `String s1 = "15 "` there is a white space at the end may be typo ( _never mind_ ) so can not be parsed... :) – akash May 08 '14 at 02:56
  • It was a typo. However you can deal with leading and trailing spaces with a .trim() call. Thanks – Garret May 08 '14 at 03:07