0

my text file :

3.456  5.234 Saturday 4.15am
2.341  6.4556 Saturday 6.08am

At first line, I want to read 3.456 and 5.234 only. At second line, I want to read 2.341 and 6.4556 only. Same goes to following line if any.

Here's my code so far :

InputStream instream = openFileInput("myfilename.txt");


                if (instream != null) {             


              InputStreamReader inputreader = new InputStreamReader(instream);
              BufferedReader buffreader = new BufferedReader(inputreader);

                      String line=null;


                while (( line = buffreader.readLine()) != null) {



        }

                                       }
nani
  • 389
  • 9
  • 32

2 Answers2

0

Thanks for showing some effort. Try this

while (( line = buffreader.readLine()) != null) {
    String[] parts = line.split(" ");
    double x = Double.parseDouble(parts[0]);
    double y = Double.parseDouble(parts[1]);
}

I typed this from memory, so there might be syntax errors.

Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111
  • @doraemon: The while loop should loop. Put a System.out.println(line); as the first line after the while and see what you get as output. – Gilbert Le Blanc Jul 11 '13 at 16:28
0
int linenumber = 1;    
while((line = buffreader.readLine()) != null){
   String [] parts = line.split(Pattern.quote(" "));
   System.out.println("Line "+linenumber+"-> First Double: "+parts[0]+" Second Double:"
+parts[1]);
linenumber++;
}

The code of Bilbert is almost right. You should use a Pattern and call quote() for the split. This removes all whitespace from the array. Your problem would be, that you have a whitespace after every split in your array if you do it without pattern. Also i added a Linenumber to my output, so you can see which line contains what. It should work fine

Basti
  • 1,117
  • 12
  • 32