• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 373
  • Last Modified:

Read text file

Hi,

I am trying to read a text file that contains some questions and an answer.
The structure of the text file is
q1   my question
a   option1
b  option2
ans   b

i want to create a question object, and write a method that returns a question object to read the file  so i can use it for multiple questions. Im confused on how to read the file .
Thanks
0
aannan
Asked:
aannan
  • 7
  • 5
  • 4
  • +4
1 Solution
 
bgloddeCommented:
A simple example:

try {
        BufferedReader in = new BufferedReader(new FileReader("questionfile.txt"));
        String str;
        while ((str = in.readLine()) != null) {
            process(str);      // process each line, creating your question object
        }
        in.close();
} catch (IOException e) {
}

http://javaalmanac.com/egs/java.io/ReadLinesFromFile.html
http://www.google.com/search?hl=en&q=java+read+text+file

Hope that helps!
0
 
aannanAuthor Commented:
I can read the file, i dont know how to assign to the instance variables of my object. my question is how do i excatly process the each line ?
Thanks
0
 
jfredricksonCommented:
You can also just use a scanner:

Scanner fileScan = new Scanner (new File("file.txt"));  // Import the file

while (fileScan.hasNext())  // While it hasn't reached the end
{
      if (fileScan.findInLine(myQuestion) != null)  // If it finds myQuestion
      {
            option1 = fileScan.nextString();  // the next word after it finds myQuestion
            option2 = fileScan.nextString();  // the word after that
      }
      
      fileScan.nextLine();  // Advance to the next line in the file
}

However, this assumes that your file is set up as:

myQuestion option1 option2
myQuestion option1 option2
myQuestion option1 option2
myQuestion option1 option2
etc...

Then it simply searches each line for a particular myQuestion, and if it finds it, sets option1 and option2 to the values immediately following that question in the line. Of course you would need to modify this a bit to fit the formatting of your text file, but this should give you an idea of how it can work.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
aannanAuthor Commented:
J,
Understand ur code but my file structure is different. Basically I have one question and then underneath it are the choises. I guess i am confused how to read each like and then store it in its appropriate instance variable.Thanks
0
 
CEHJCommented:
I did something like this a long time ago. I think there's an example here:

http://www.sigma-software.freeserve.co.uk/applets/QandAbase/QandAApp.htm
0
 
gauravkrtomarCommented:
U can have a class as:-
class Question{
  String ques;  //stores question
  String[] options=new String[upperLimit]; //stores options
  int answer=-1; //keeps the index of the correct answer
 //u can have getters and setters for the ques, options and answer
}

U can then start reading the complete file line by line:-
u can check that the line starts with q then instantiate a Question object and that to the list of questions after that wat u'll get will be the question, then go to next line and that'll be u r option, u can have a if statements there so that u can add the correct option to the correct option array index, if line starts with a assign it to options[0] if it is b then assign it to options[1] and so on.
And if line starts with the ans then that will be the correct answer.

Ask if i sound confusing :)
0
 
CEHJCommented:
What i did is to put an asterisk on the end of the correct answer in the text file and then trimmed it off before displaying it
0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> class Question{

Yes, that would be the right way to do it. Maybe I would keep an ArrayList instead of an array.
0
 
WebstormCommented:
You can still use an array, but created by java.util.Vector for example :

  String[] options; //stores options

...
    Vector voptions=new Vector();
    ... options.add( option );
    options=(String[])voptions.toArray(new String[voptions.size()]);

0
 
WebstormCommented:
for reading the file, use String.startsWith :

    String line; // the line you read from the file
    Question qst; // the current question you're creating
     ...
       if (line.startWith("q")) qst=new Question( line.substring(1).trim() );
       else if (line.startWith("ans")) qst.answer="abcdefgh".indexOf( line.subtring(3).trim().charAt(0) );
       else voptions.add(line.substring(1).trim());

0
 
aannanAuthor Commented:
gauravkrtomar,

I have written the qustions class and i am more familiar with arraylists, if so how do i add the options into the arraylist. Thanks
if you can give me a pseudocode i can follow it much easier. I am still not conversant with java syntax yet. Thanks
0
 
CEHJCommented:
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Use the same code as Webstorm. Instead of Vector, use ArrayList.
0
 
gauravkrtomarCommented:
/*
Assuming that reader is the buffered reader
*/
ArrayList questionList=new ArrayList();
String line; // the line you read from the file
while((line=reader.readLine())!=null){
    Question qst; // the current question you're creating
     ...
    if (line.startWith("q")){
       qst=new Question( line.substring(1).trim() );
       questionList.add(qst);
    }
    else{
       qst=questionList.get(questionList.size()-1);//gets the last question
       if (line.startWith("ans")) qst.answer="abcdefgh".indexOf( line.subtring(3).trim().charAt(0) );
       else qst.voptions.add(line.substring(1).trim());
    }
}
0
 
aannanAuthor Commented:
I tried modifying and using this code and i got a lot of errors.
this was the class i used for 'questions'
=========================

import java.util.ArrayList;

public class Questions {
            private String question;
            private ArrayList<String> options;
            private String answer;

      public Questions( String question, ArrayList<String> options, String answer){
              setQuestion(question);
              setOptions(options);
              setAnswer(answer);
      }

      public String getAnswer() {
            return answer;
      }

      public void setAnswer(String answer) {
            this.answer = answer;
      }

      public ArrayList<String> getOptions() {
            return options;
      }

      public void setOptions(ArrayList<String> options) {
            this.options = options;
      }

      public String getQuestion() {
            return question;
      }

      public void setQuestion(String question) {
            this.question = question;
      }
}
0
 
gauravkrtomarCommented:
What are the errors you are getting, plus you can have one more function in the Question class:-

public void addOption(String option){
  options.add(option);
}
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Do you have Java 5?
0
 
WebstormCommented:
Don't forget to replace
       startWith
by
       startsWith
0
 
aannanAuthor Commented:
Yes I am using java 5.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
What were the errors and at what lines?
0
 
aannanAuthor Commented:
this is my method to read questions and return them as an ArrayList.
im getting errors here : ---->

static ArrayList<String> readQuestions (HttpServlet srv, String fname){
            InputStream is = srv.getServletContext().getResourceAsStream(fname);
            
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            
            String question =  reader.readLine();
            ArrayList<String> questionList=new ArrayList<String>();
            String line;
            while((line=reader.readLine())!=null){
                Questions myQuestions;
                if (line.startsWith("Q")){
                -->      myQuestions=new Questions( line.substring(1).trim() );// Questions(String) is undefined
                    -->  questionList.add(myQuestions);
                }
                else{
                      myQuestions=questionList.get(questionList.size()-1); // cannot convert from object to questions
                   if (line.startsWith("Correct")){
                       -->  myQuestions.answer="abcdefgh".indexOf( line.substring(3).trim().charAt(0) ); // Questions.answer is not visible
                   }
                  -->  else myQuestions.options.add(line.substring(1).trim()); // Questions.options.not visible
                }
            }
             

here is my Questions class again
======================
package millions;
import java.util.ArrayList;

public class Questions {
          private String question, answer;
          private ArrayList<String> options;
          private int value;

      public Questions( String question, ArrayList<String> options, String answer, int value){
            setQuestion(question);
            setOptions(options);
            setAnswer(answer);
            setValue(value);
     }

     public String getAnswer() {
          return answer;
     }

     public void setAnswer(String answer) {
          this.answer = answer;
     }

     public ArrayList<String> getOptions() {
          return options;
     }

     public void setOptions(ArrayList<String> options) {
          this.options = options;
     }

     public String getQuestion() {
          return question;
     }
     public void addOption(String option){
           options.add(option);
     }

     public void setQuestion(String question) {
          this.question = question;
     }
     
     public int getValue() {
                  return value;
            }

            public void setValue(int value) {
                  this.value = value;
            }
}
thanks
0
 
gauravkrtomarCommented:
//static ArrayList<String> readQuestions (HttpServlet srv, String fname){
//u r adding Question objects to a arraylist that can contain only the String objects
static ArrayList<Questions> readQuestions (HttpServlet srv, String fname){
          InputStream is = srv.getServletContext().getResourceAsStream(fname);
         
          BufferedReader reader = new BufferedReader(new InputStreamReader(is));
         
          String question =  reader.readLine();
//          ArrayList<String> questionList=new ArrayList<String>();
          ArrayList<Questions> questionList=new ArrayList<Questions>();
          String line;
          while((line=reader.readLine())!=null){
              Questions myQuestions;
              if (line.startsWith("Q")){
              -->     myQuestions=new Questions( line.substring(1).trim() );// Questions(String) is undefined
//u have no constructor which can take String as the argument
//add this to Questions class:-
/**
 public Questions( String question){
            setQuestion(question);
            setOptions(new ArrayList<String>());
     }
**/
                  -->  questionList.add(myQuestions);
              }
              else{
                   myQuestions=questionList.get(questionList.size()-1); // cannot convert from object to questions
                 if (line.startsWith("Correct")){
                    -->  myQuestions.answer="abcdefgh".indexOf( line.substring(3).trim().charAt(0) ); // Questions.answer is not visible
                          myQuestions.setAswer("abcdefgh".indexOf( line.substring(3).trim().charAt(0)));
//also u need to change the logic here as the answer u have specified is String and the value that u r getting here is int
//so just change the code so that u have correct values in the correct variable i.e. value and answer( i am not sure for what u r using value and for what u r using answer)
                 }
                -->  else myQuestions.addOption(line.substring(1).trim()); // Questions.options.not visible
//add the following method in the Questions class:-
/*
public void addOption(String option){
  options.add(option);
}
*/
              }
          }
0
 
aannanAuthor Commented:
thanks!
0
 
gauravkrtomarCommented:
:-)     welcome.
0
 
WebstormCommented:
thanks to my comments too !!!!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 7
  • 5
  • 4
  • +4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now