I have some trouble reading file in Java.
What a file looks like:
Answer 1:
1. This is an apple
2. Something
Answer 2:
1. This is a cool website
2. I love banana
3. This is a table
4. Programming is fun
Answer 3.
1. Hello World
....
What I want to do is separate them into two items:
One is the Answer number; The other one is list of answers.
So assuming I have a object class called Answer:
String of answer number
List of answers.
This is what I have done so far to debug my code before I put it into object class. But I’m not able to get the correct result
public void reader(String file) throws FileNotFoundException, IOException {
FileReader fR = new FileReader(file);
BufferedReader bR = new BufferedReader(fR);
String line = null;
int count = 0 ;
String blockNum = "";
String printState = "" ;
while ((line = bR.readLine()) != null) {
if(line.contains("Answer")){
//System.out.println("Contain Answer statement: " + line);
count++;
blockNum = line;
printState = "";
}
else{
//System.out.println("No Answer Statement: " + line);
printState += line + " / " ;
}
System.out.println( count + " " + blockNum + " " + printState );
}
// Close the input stream
bR.close();
fR.close();
}
I’m pretty sure I did something stupid while I’m coding. I’m not too sure how to read it so that it will have separate it.
Right now the output looks like this:
1 Answer 1:
1 Answer 1: 1. This is an apple /
1 Answer 1: 1. This is an apple / 2. Something /
2 Answer 2:
2 Answer 2: 1. This is a cool website /
2 Answer 2: 1. This is a cool website / 2. I love banana /
2 Answer 2: 1. This is a cool website / 2. I love banana / 3. This is a table /
2 Answer 2: 1. This is a cool website / 2. I love banana / 3. This is a table / 4. Programming is fun /
3 Answer 3.
3 Answer 3. 1. Hello World /
But I want the output to be something like this:
1 Answer 1: 1. This is an apple / 2. Something /
2 Answer 2: 1. This is a cool website / 2. I love banana / 3. This is a table / 4. Programming is fun /
3 Answer 3. 1. Hello World /
One solution use a flag for printTime as a boolean.
add a little extra print at the end of the while for last answer
that way you can have several printState for one answer in one line.
But correct “java” way of handle this is to create your objects:
and only after print them out 🙂
Simpler solution is to use a