The quieter you are, the more you are able to hear.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
SCJP
Visit my download page
Randall Twede wrote:i am guessing his problem is with getting the second sentence in each line. it has been so long since i have done that i can't remember how. StringTokenizer comes to mind. i am sure there are tutorials about this. try going to google and typing in java parse text file
The quieter you are, the more you are able to hear.
SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
The quieter you are, the more you are able to hear.
Kemal Sokolovic wrote:You were already advised against using StringTokenizer, and I agree with the point.
Much easier and elegant solution can be achieved by using String#split(String) method I have referred you to in my previous post. If you have a String like this:
you can get each value with the code like this:
With that code you will have these values:
data[0] = "value1";
data[1] = "value2";
data[2] = "value3";
data[3] = "value4";
As you can see the logic is pretty straighforward. For more information you can look the API or tutorial, but with the given example you should be able to accomplish your task.
Phil English wrote:Your x variable it incrementing with the line not the token. If your text file is only ever structured as you say then you know that the second element of a will be the string you require for each line of your program.
Phil English wrote:What is happening in your latest code is that you are calling x++ every time you read a new line so x==2 will only be true on your second line. What is happening is that your code is printing all of the String array a only on the second line.
Let's say you run your code just for the first two lines of the file.
On the first iteration your String array a will contain ["AAA", "BBB", "CCC"] so a[0] = "AAA", a[1] = "BBB", a[2] = "CCC"
On the second iteration a is overwritten and now contains ["AAA", "BBB", "CCC"] so a[0] = "AAA1", a[1] = "BBB1", a[2] = "CCC1"
As a suggestion get rid of the if and the for loop and just try printing individual elements of the array. System.out.println(a[0])
Phil English wrote:You know that every time you loop (each line in your file) that a[1] contains the string you want. Why not extract that on every iteration into a new variable. That new variable will grow by one element each time you iterate and when you are finished it will contain all the strings you want.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |