An arraylist question

Hello everyone!
I am writing a java project to record the clicked numbers of the threads in a specific forum. I created 2 tables in a MySql database to store the thread information and clicked number respectively.
ThreadInfo Table:
thread_id | thread_title() | thread_link | thread_author | submitting_timeThreadFeedback Table:
thread_id | clicked | replied | at_timeWhen I got a new piece of thread information such as
(thread_title, thread_link, thread_author, clicked, replied, at_time)First I check if this thread has been recorded according to its link. If yes, I fetch its existed thread_id from ThreadInfo table and then record its new clicked and replied number in the ThreadFeedback table. If it has not been recorded, I generate a new thread_id that has not been used and insert it to the ThreadInfo Table.
For efficiency's sake, I don't want to query the database many times. So at the beginning, I read all the information I needed from the database with
"SELECT thread_id, thread_hplink FROM ThreadInfo;" As I will have many new pieces of thread information and the resultset is usually used for only one iteration, I dumped the information in the resultset into two ArrayList objects: UUIDList and ThreadLinkList and tried to let the element UUIDList(i) stores the UUID of element ThreadHplinkList(i) with
     String str="SELECT thread_id, thread_hplink "+
     "FROM TianyazatanThreadInfo;";
     ResultSet rltThread=stmnt.executeQuery(str);
     while(rltThread.next())
     str=rltThread.getString("thread_id");
     UUIDList.add(str);
     str=rltThread.getString("thread_hplink");
     ThreadHplinkList.add(str);
     }                    The problem I encountered is that when I try to use
     for(int i=0;i<ThreadHplinkList.size();i++)
       str=ThreadHplinkList.get(i);
       if(str.trim()==threadHplink.trim())
                    boolean threadExisted=true;
                    uuid=UUID.fromString(UUIDList.get(i));
         break;
     }to identify if the thread has been recorded. The above codes return threadExisted false even if the following code returns threadExisted true
     existed=ThreadHplinkList.contains(threadHplink);But if I use .containes to check the existence of the thread, how can I get its correponding
thread_id?

Yes, kajbj. Your suggestion is very helpful. I will try.
But why the iteration of ArrayList returns false answer?

Similar Messages

  • A TreeMap and ArrayList question

    I am considering using a TreeMap structure with a String as my key and an ArrayList<Record> as my value. After doing some searching and not quite finding the assurance I desired, I am looking for anyone's guidance on my approach. Allow me to briefly explain my situation.
    I am writing a program which reads a entry log and breaks the information into a more usable form (in particular, separated by each individual). I do not know before hand the names of the people I may encounter in the log, nor how many occurances of their name I may find. Also, it is safe to assume that no one person's name is the same for two different people. I wish to be able to call up a person's name and view all records associated with them. I felt the use of a TreeMap would be best in the event that I wish to list out a report with all individuals found, and such a listing would already be in alphabetical order.
    In summation, is my approach of making a TreeMap<String, ArrayList<Record>> an acceptable practice?
    Thank you for your time.

    Puce wrote:
    >
    If there's the slightest chance, OP, that you'll have to do something other than simply look up records by name, consider an embedded DB. If there's the slightest chance that Ron Manager will come along on Monday and say "Good job! Now, can we look up records by date?" or something, consider an embedded DB."Embedded DB" is something different than "in-memory DB" though. An embedded DB is persistent while a in-memory one is not. If you use an embedded DB, you need to synchronize it after restart with your other data sources, and it will use disk space as well. There are use case for embedded DBs and others for in-memory DBs. Hard to say which is the case here, without knowing more.The OP "isn't allowed" to use a database, which almost certainly means he's not allowed to install any more software on the system, eg, MySQL. So an in-process database is the way to go. Whether it's persistent or not is irrelevant. "Embedded" and "in-memory" are not opposites. By "embedded" we really mean in-process. Do you know of any databases which can run in-process but not in-memory? How about in-memory but not in-process? In reality, we're talking about the same products, configured slightly differently.

  • ArrayList question. How to remove an Item

    I have an array collection that is going to contain a list of username.
    I would like to fine one of the names and remove it from a list. How could I do this.
    I am an Actionscript programmer so if I where to do this in AS I would do it like this.
    for(var i:int=0; i<myarray.length; i++)
          if(myarray[i] == "matthew")
          myarray.remove(i);
    }in Java I am not seeing a length property for the ArrayList

    7biscuits wrote:
    ArrayList al = new ArrayList();
    al.add("aa");
    al.add("ab");
    al.add("ac");
    al.add("ad");
    for(int i=0; i<al.size(); i++){
    if(al.get(i)=="ac"){
    al.remove(i);
    }here "ac" is removed from the arraylistAll I can do is shake my head and chuckle (and sigh).
    Don't use == to compare Strings, and did you not read the rest of the thread that said it is not necessary to use the index? Not to mention, to either you or the OP, that 2 seconds of looking at the API docs would have let the both of you come to that same conclusion.
    Also, if you do remove items in an ArrayList in this manner (for whatever reason) then loop through the ArrayList backwards, or you will skip an element every time you remove one.
    Too little, too late, and so off target.

  • How to store the data of a file into an ArrayList?

    Hi! everyone.
    I want to know
    if I have a File, and the data in the file are type int, type String...
    And I have a ArrayList which is of type Question
    How do I store the data of that file into the ArrayList
    I tried to use the while loop(use the hasNextLine() to read the data line by line)
    But I cannot add data which are not of type Question to the ArrayList.
    Can you tell me what I should do, please?
    I also wonder that
    The data of the file are of many types, but when I try to read it with the nextLine(), the data all turn out to be of type String. Why?
    Thank you.
    Edited by: Terry001 on Apr 30, 2008 1:13 PM

    No, a line in the file is just part of a question
    The format of the file is like this:
    *<question type code>                    :     String*
    *<question point value>                    :     int*
    *<question category>                         :     String*
    *<question difficulty level>               :     int*
    *<question text>                              :     String*
    *<question correct answer>               :     String*
    *<optional question-specific data>     :     String*
    *<question terminator>                    :     String*
    And here is an example
    TF //TrueFalseQuestion
    5 //points value
    None //category
    3 //difficulty level
    The capital of the United States is Washington, D.C. //question text
    True // answer
    *** //quetion terminator
    I created an ArrayList in the Test class:
    private ArrayList<Question> questions; // Create inside constructor
        public Test (String name, String instr)
            testName = name;
            scoreEarned = 0;
            scorePossible = 0;
            instructions = instr;
            questions = new ArrayList<Question>(); //[MAX_NUMBER_OF_QUESTIONS];
        }And I tried to use the following method to store the data of the file to the ArrayList
    // This method loads a set of questions from a plain text file
        public void loadQuestionsFromFile(String fileName) throws FileNotFoundException
            try
                File fileReader = new File("input.txt");
                Scanner sc = new Scanner(fileReader);
                while (sc.hasNextLine())
                    // I don't know how to pass the data I got from the nextLine() method to the ArrayList because they are of different type
            catch (FileNotFoundException a)
                System.out.println(a);
        }    As all you said, I should create an Question object in the while loop
    Question temp = new Question ();But I have no idea how to pass the int and String to the Question object.
    Thank you

  • Questions about a MasterQuize program

    Hi, everyone.
    I got a in-class case study program like this in the class:
    * This class stores/represents a question that has one of two
    * answers: True or False.
    * <p></p>
    * It needs to track the following information:
    * <ul>
    * <li>Question text</li>
    * <li>Correct answer</li>
    * <li>The user's answer to the question</li>
    * <li>Points value</li>
    * <li>Category</li>
    * <li>Difficulty rating</li>
    * </ul>
    // Our question should allow us to do the following:
    // - Create question (constructor) -- may be overloaded
    // - Print (display) question
    // - Check client's answer for correctness
    // - Get points value for question (0 or max)
    //   - Add "No-BS" grading option
    // - Getting client's answer
    // - Check to see if answered by client
    public class TrueFalseQuestion
        // Class constants (to simplify changes to common values)
        public static final int MIN_DIFFICULTY_LEVEL = 1;
        public static final int MAX_DIFFICULTY_LEVEL = 5;
        public static final int DEFAULT_DIFFICULTY_LEVEL = 1;
        public static final int DEFAULT_POINT_VALUE = 1;
        public static final String DEFAULT_CATEGORY_VALUE = "none";
        // Class instance variables
        private String questionText;
        private String correctAnswer;
        private String userAnswer;
        private int pointsValue;
        private String category;
        private int difficultyLevel; // TODO: Set a range for difficulty levels
         * @param text The literal wording of this question
         * @param answer The correct answer for this question
         * @param pts The total points available for this question
         * @param ctgry Category keyword for this question
         * @param level The perceived/intended difficulty level of this question
         * <p></p>
         * Defines a TrueFalseQuestion object.
        public TrueFalseQuestion (String text, String answer, int pts, String ctgry, int level)
            // Set starting values for all instance variables
            questionText = text.trim();
            correctAnswer = answer.trim();
            userAnswer = null; // No user answer supplied yet
            if (pts >= 1) // We assume that every problem is worth at least 1 point
                pointsValue = pts;
            else
                pointsValue = DEFAULT_POINT_VALUE;
            category = ctgry.trim();
            if (level >= MIN_DIFFICULTY_LEVEL && level <= MAX_DIFFICULTY_LEVEL) // within range
                difficultyLevel = level;
            else
                difficultyLevel = DEFAULT_DIFFICULTY_LEVEL;
        // Simplified (overloaded) constructors
         * @param text The literal wording of this question
         * @param answer The correct answer for this question
         * @param pts The total points available for this question
         * <p></p>
         * Defines a TrueFalseQuestion with default values for category and difficulty level.
        public TrueFalseQuestion (String text, String answer, int pts)
            // Call pre-existing constructor with default category and difficulty
            this(text, answer, pts, DEFAULT_CATEGORY_VALUE, DEFAULT_DIFFICULTY_LEVEL);
         * @param text The literal wording of this question
         * @param answer The correct answer for this question
         * <p></p>
         * Defines a TrueFalseQuestion with the default point value, default category,
         * and default difficulty level.
        public TrueFalseQuestion (String text, String answer)
            // Call pre-existing constructor with default points, category and difficulty
            this(text, answer, DEFAULT_POINT_VALUE, DEFAULT_CATEGORY_VALUE,
                 DEFAULT_DIFFICULTY_LEVEL);
         * @param text The literal wording of this question
         * @param answer The correct answer for this question
         * @param pts The total points available for this question
         * @param ctgry Category keyword for this question
         * <p></p>
         * Defines a TrueFalseQuestion with the default difficulty level.
        public TrueFalseQuestion (String text, String answer, int pts, String ctgry)
            // Call pre-existing constructor with default points, category and difficulty
            this(text, answer, pts, ctgry,
                 DEFAULT_DIFFICULTY_LEVEL);
         * @param text The literal wording of this question
         * @param answer The correct answer for this question
         * @param ctgry Category keyword for this question
         * <p></p>
         * Defines a TrueFalseQuestion with the default point value and the default
         * difficulty level.
        public TrueFalseQuestion (String text, String answer, String ctgry)
            // Use default points and difficulty
            this(text, answer, DEFAULT_POINT_VALUE, ctgry, DEFAULT_DIFFICULTY_LEVEL);
         * @param text The literal wording of this question
         * @param answer The correct answer for this question
         * @param pts The total points available for this question
         * @param level The perceived/intended difficulty level of this question
         * <p></p>
         * Defines a TrueFalseQuestion with the default value for the question category.
        public TrueFalseQuestion (String text, String answer, int pts, int level)
            // Use default category
            this(text, answer, pts, DEFAULT_CATEGORY_VALUE, level);
        // Clients can invoke this method to retrieve the text of the current question.
        // We chose to return the text instead of printing it; this allows the client
        // to decide how it should be presented (via a GUI, over a network, etc.)
        public String getQuestion ()
            return questionText;
        // This method allows the client to store the user's answer inside the
        // TrueFalseQuestion object for easy comparison
        public void submitAnswer (String ans)
            userAnswer = ans;
        // This method reports whether the submitted answer matches the correct answer
        public boolean answerIsCorrect(String userAns) // This version does all the work
            if (userAns == null) // No response from user (yet)
                return false;
            else
                // Normalize and compare answers
                char key = normalize(correctAnswer); // Get 't' or 'f'
                char ans = normalize(userAns); // Get 't' or 'f'
                return (key == ans);
        public boolean answerIsCorrect ()
            return answerIsCorrect(userAnswer); // Call previously-defined version
        public int getPointsValue()
            return pointsValue;
        // Return the points awarded for the user's answer. This method does
        // NOT support partial credit; answers are either correct or incorrect.
        // If the "No-BS" option is selected, blank (unanswered) questions receive
        // 1 point automatically; otherwise, the score will be either 0 or the
        // question's normal points value.
        public int getPointsEarned(boolean useNoBSRule)
    System.out.println("useNoBS: " + useNoBSRule + "\tuserAnswer: " + userAnswer + "\tcorrectAnswer: " + correctAnswer);
            if (useNoBSRule && (userAnswer == null))
                return 1;
            else if (userAnswer == null)
                return 0; // Without "No-BS", treat blank problems as incorrect
            if (answerIsCorrect() == false)
                return 0;
            else
                return pointsValue;
        // This method returns true if the user has submitted an answer
        // for this question (regardless of whether that answer is correct)
        public boolean hasBeenAnswered ()
            return (userAnswer != null);
        // Private helper method to convert all answers to single lowercase
        // letters (in this case, 't' for TRUE and 'f' for FALSE)
        private char normalize (String input)
             if (input != null)
                  input = input.trim(); // Remove leading whitespace
                  input = input.toLowerCase();
                  return input.charAt(0);
             else
                  return ' ';
    import java.util.*;
    * This class represents a complete test or quiz.
    * Data stored:
    * - List of questions
    * - Total score earned
    * - Total score possible
    * - Name/title of test
    * - Instructions
    *  - Category/class assignment
    *  - Student (test-taker) name
    *  - Date test is/was taken
    *  - Time started
    *  - Time completed
    *  - Maximum time allotted
    *  - (List of) Maximum attempts per question
    *  - List of attempts per question
    *  - List of difficulty ratings per question
    *  - Assignment weight
    * Methods:
    * - Constructor
    * - Add question
    * - Display question
    * - Display test
    * - Display instructions
    *      - Generate random exam
    * - Take/administer test
    * - Get score
    * STUFF TO DO:
    * - Add time/date restrictions
    * - Add network access restrictions
    * - Add other restrictions/allowances?
    * @author (your name)
    * @version (a version number or a date)
    public class Test
        // Class constant
        public static final int MAX_NUMBER_OF_QUESTIONS = 10;
        // Class instance variables
        private String testName;
        private int scoreEarned; // What the student earned on the exam
        private int scorePossible; // Total point values of all questions
        private String instructions; // Exam header text
        private ArrayList<TrueFalseQuestion> questions; // Create inside constructor
        // Methods
        public Test (String name, String instr)
            testName = name;
            scoreEarned = 0;
            scorePossible = 0;
            instructions = instr;
            questions = new ArrayList<TrueFalseQuestion>(); //[MAX_NUMBER_OF_QUESTIONS];
        public String getInstructions()
            return instructions;
        public int getScore()
            return scoreEarned;
        public void addQuestion (TrueFalseQuestion q)
            scorePossible += q.getPointsValue();
            questions.add(q); // Automatically append question to end of test
        public String displayQuestion (int position)
            if (position < questions.size())
                return (position+1) + ". " + questions.get(position).getQuestion();
            else
                return null;
        public String displayTest ()
            String result = "";
            for (int i = 0; i < questions.size(); i++)
                result += (i+1) + ". (";
                TrueFalseQuestion t = questions.get(i);
                result += t.getPointsValue();
                result += " points)\n\n" + displayQuestion(i);
                result += "\n\n";
            return result;
        // Get test length (number of questions)
        public int length ()
             return questions.size();
        // Submit answer to a specific question
        public boolean answer(int number, String a)
             // Question numbers run from 0-(max-1) -- THIS WAS AN OFF-BY-ONE ERROR AT FIRST
             if (number >= 0 && number < questions.size())
                  TrueFalseQuestion t = questions.get(number);
                  t.submitAnswer(a);
                  return true; // Question was answered
             else
                  return false; // Unable to answer (nonexistent) question
        // Score exam
        public void scoreExam (boolean useNoBS)
             scoreEarned = 0;
             for (int i = 0; i < questions.size(); i++) // For each question in exam
                  TrueFalseQuestion t = questions.get(i); // get current question
                  scoreEarned += t.getPointsEarned(useNoBS);
    }// Test harness for the Test and *Question classes
    import java.util.*;
    public class QuizDriver
         public static void main(String[] args)
              // Create a new Test object
              Test exam = new Test("Sample Exam", "Select the correct answer for each question");
              setUp(exam);
              Scanner sc = new Scanner(System.in);
              System.out.println(exam.getInstructions());
              // Administer exam
              for (int i = 0; i < exam.length(); i++)
                   // Print out current question
                   System.out.println(exam.displayQuestion(i));
                   // Get user answer
                   System.out.print("Your answer: ");
                   String ans = sc.nextLine();
                   if (ans.equals("")) // Handle blank responses for unanswered questions
                        ans = null;
                   exam.answer(i, ans);
              // Get exam results
              exam.scoreExam(true);
              System.out.println("Your final score was " + exam.getScore() + " points.");
         private static void setUp (Test t)
              TrueFalseQuestion x = new TrueFalseQuestion("The sky is blue.", "true", 2);
              t.addQuestion(x);
              x = new TrueFalseQuestion("The first FORTRAN compiler debuted in 1957", "true", 5);
              t.addQuestion(x);
              x = new TrueFalseQuestion("Spock was a Vulcan", "false", 3);
              t.addQuestion(x);
    }This program is far from finishing.
    I have many questions about this program, but let me ask this one first:
    In the TrueFalseQeustion class, why are there so many constructors? What is the purpose of setting some of the variables to default values?
    Thank you very much!!!
    Edited by: Terry001 on Apr 16, 2008 10:02 AM

    newark wrote:
    Stop ignoring the error messages. You seem to think that an error message means you're doing the assignment wrong. It's probably a simple fix. Post the exact error messages, as well as the code that corresponds to them. The error message will tell you exactly what line the problem occurs on, so you know right where to look.Hi,
    After some modifications, the program now gives me the result the assignment wants when I run it. But I still have trouble with the MultipleChoiceQuestion class
    Here is the complete program
    QuizDriver class
    // Test harness for the Test and *Question classes
    import java.util.*;
    public class QuizDriver
         public static void main(String[] args)
              // Create a new Test object
              Test exam = new Test("Sample Exam", "Select the correct answer for each question");
              setUp(exam);
              Scanner sc = new Scanner(System.in);
              System.out.println(exam.getInstructions());
              // Administer exam
              for (int i = 0; i < exam.length(); i++)
                   // Print out current question
                   System.out.println(exam.displayQuestion(i));
                   // Get user answer
                   System.out.print("Your answer: ");
                   String ans = sc.nextLine();
                   if (ans.equals("")) // Handle blank responses for unanswered questions
                        ans = null;
                   exam.answer(i, ans);
              // Get exam results
              exam.scoreExam(true);
              System.out.println("Your final score was " + exam.getScore() + " points.");
         private static void setUp (Test t)
                                   Question x;
              x = new TrueFalseQuestion("The sky is blue.", "true", 2);
              t.addQuestion(x);
              x = new TrueFalseQuestion("The first FORTRAN compiler debuted in 1957", "true", 5);
              t.addQuestion(x);
              x = new TrueFalseQuestion("Spock was a Vulcan", "false", 3);
              t.addQuestion(x);
              x = new MultipleChoiceQuestion("What is the color of the car\na.Red\nb.Green", "a. Red", 3);
              t.addQuestion(x);
              x = new MultipleChoiceQuestion("What is the name of this class\na.CSE110\nb.CSE114", "b, CSE114", 3);
              t.addQuestion(x);
    }Test
    public class Test
        // Class constant
        public static final int MAX_NUMBER_OF_QUESTIONS = 10;
        // Class instance variables
        private String testName;
        private int scoreEarned; // What the student earned on the exam
        private int scorePossible; // Total point values of all questions
        private String instructions; // Exam header text
        private ArrayList<Question> questions; // Create inside constructor
        // Methods
        public Test (String name, String instr)
            testName = name;
            scoreEarned = 0;
            scorePossible = 0;
            instructions = instr;
            questions = new ArrayList<Question>(); //[MAX_NUMBER_OF_QUESTIONS];
        public String getInstructions()
            return instructions;
        public int getScore()
            return scoreEarned;
        public void addQuestion (Question q)
            scorePossible += q.getPointsValue();
            questions.add(q); // Automatically append question to end of test
        public String displayQuestion (int position)
            if (position < questions.size())
                return (position+1) + ". " + questions.get(position).getQuestion();
            else
                return null;
        public String displayTest ()
            String result = "";
            for (int i = 0; i < questions.size(); i++)
                result += (i+1) + ". (";
                Question t = questions.get(i);
                result += t.getPointsValue();
                result += " points)\n\n" + displayQuestion(i);
                result += "\n\n";
            return result;
        // Get test length (number of questions)
        public int length ()
             return questions.size();
        // Submit answer to a specific question
        public boolean answer(int number, String a)
             // Question numbers run from 0-(max-1) -- THIS WAS AN OFF-BY-ONE ERROR AT FIRST
             if (number >= 0 && number < questions.size())
                  Question t = questions.get(number);
                  t.submitAnswer(a);
                  return true; // Question was answered
             else
                  return false; // Unable to answer (nonexistent) question
        // Score exam
        public void scoreExam (boolean useNoBS)
             scoreEarned = 0;
             for (int i = 0; i < questions.size(); i++) // For each question in exam
                  Question t = questions.get(i); // get current question
                  scoreEarned += t.getPointsEarned(useNoBS);
    }Question
    public class Question
    // Class constants
      public static final int MIN_DIFFICULTY_LEVEL = 1;
      public static final int MAX_DIFFICULTY_LEVEL = 5;
      public static final int DEFAULT_DIFFICULTY_LEVEL = 1;
      public static final int DEFAULT_POINT_VALUE = 1;
      public static final String DEFAULT_CATEGORY_VALUE = "none";
      // Class instance variables
      protected String questionText;
      protected String correctAnswer;
      protected String userAnswer;
      protected int pointsValue;
      protected String category;
      protected int difficultyLevel; //TODO: set a range for difficulty levels
      // Constructors
      public Question (String text, String answer, int pts, String ctgry, int level)
          questionText = text.trim();
          correctAnswer = answer.trim();
          userAnswer = null;
          if (pts >= 1)
              pointsValue = pts;
            else
                pointsValue = DEFAULT_POINT_VALUE;
            category = ctgry.trim();
            if (level >= MIN_DIFFICULTY_LEVEL && level <= MAX_DIFFICULTY_LEVEL)
                difficultyLevel = level;
            else
                difficultyLevel = DEFAULT_DIFFICULTY_LEVEL;
        // Overloaded (simplied) constructors
        public Question (String text, String answer, int pts)
            this(text, answer, pts, DEFAULT_CATEGORY_VALUE, DEFAULT_DIFFICULTY_LEVEL);
        public Question (String text, String answer, int pts, String ctgry)
            this(text, answer, pts, ctgry, DEFAULT_DIFFICULTY_LEVEL);
        public Question (String text, String answer, String ctgry)
            this(text, answer, DEFAULT_POINT_VALUE, ctgry, DEFAULT_DIFFICULTY_LEVEL);
        public Question (String text, String answer, int pts, int level)
            this(text, answer, pts, DEFAULT_CATEGORY_VALUE, level);
        // Methods
        public String getQuestion ()
            return questionText;
        // Use this method to store user answers
        public void submitAnswer (String ans)
            userAnswer = ans;
        public boolean answerIsCorrect (String userAns)
            if (userAns == null)
                return false;
            else
                // Normalize and compare answers
                char key = normalize (correctAnswer); //Get the first letter of an answer
                char ans = normalize (userAns); //Get the first letter of an answer
                return (key == ans);
        public boolean answerIsCorrect ()// Why do we need two answerisCorrect() methods?
            return answerIsCorrect (userAnswer);
        public int getPointsValue ()
            return pointsValue;
        public int getPointsEarned (boolean userNoBSRule)
            System.out.println ("useNoBS: " + userNoBSRule + "\tuseAnswer: " + userAnswer + "\tcorrectAnswer: " + correctAnswer);
            if (userNoBSRule && (userAnswer == null))
                return 1;
            else if (userAnswer == null)
                return 0;
            if (answerIsCorrect() == false)
                return 0;
            else
                return pointsValue;
        public String getCorrectAnswer ()
            return correctAnswer;
        public boolean hasBeenAnswered ()
            return (userAnswer != null);
        private char normalize (String input)
            if (input != null)
                input = input.trim();
                input = input.toLowerCase();
                return input.charAt(0);
            else
                return ' ';
           TrueFalseQuestion
    public class TrueFalseQuestion extends Question
      public TrueFalseQuestion (String text, String answer, int pts, String ctgry, int level)
          super(text, answer, pts, ctgry, level);
        public TrueFalseQuestion (String text, String answer, int pts)
            super(text, answer, pts, DEFAULT_CATEGORY_VALUE, DEFAULT_DIFFICULTY_LEVEL);
        public TrueFalseQuestion (String text, String answer, int pts, String ctgry)
            super(text, answer, pts, ctgry, DEFAULT_DIFFICULTY_LEVEL);
        public TrueFalseQuestion (String text, String answer, String ctgry)
            super(text, answer, DEFAULT_POINT_VALUE, ctgry, DEFAULT_DIFFICULTY_LEVEL);
        public TrueFalseQuestion (String text, String answer, int pts, int level)
            super(text, answer, pts, DEFAULT_CATEGORY_VALUE, level);
        // Methods
        public String[] getPossibleAnswerChoice ()
            String[] possibleAnswerChoice = {"true", "false"};
            return possibleAnswerChoice;
    } MultipleChoiceQuestion
    public class MultipleChoiceQuestion extends Question
       public MultipleChoiceQuestion (String text, String answer, int pts, String ctgry, int level)
           super(text, answer, pts, ctgry, level);
        public MultipleChoiceQuestion (String text, String answer, int pts)
            super(text, answer, pts, DEFAULT_CATEGORY_VALUE, DEFAULT_DIFFICULTY_LEVEL);
        public MultipleChoiceQuestion (String text, String answer, int pts, String ctgry)
            super(text, answer, pts, ctgry, DEFAULT_DIFFICULTY_LEVEL);
        public MultipleChoiceQuestion (String text, String answer, String ctgry)
            super(text, answer, DEFAULT_POINT_VALUE, ctgry, DEFAULT_DIFFICULTY_LEVEL);
        public MultipleChoiceQuestion (String text, String answer, int pts, int level)
            super(text, answer, pts, DEFAULT_CATEGORY_VALUE, level);
        // Methods
        String possibleAnswers;
        public String getPossibleAnswers ()
            return possibleAnswers;
        public void addAnswerChoice (String answerChoice)
            String ansChoice = answerChoice;
            questionText += "\nansChoice";
            possibleAnswers = answerChoice;
        public void printAnswerChoice ()
            System.out.println (questionText);
    } I don't understand why the assignment wants me to build a method in the MultpleChoiceQuestion class to store the potential answer choices, I can make the program display the potential answer choices by including them in the questionText as following in the QuizDriver class
    Question x;
    x = new MultipleChoiceQuestion("What is the color of the car\na.Red\nb.Green", "a. Red", 3);
    t.addQuestion(x); I don't know how to allow the client to construct the list of answer choices one at a time(add one potential answer choice by calling the addAsnwerChoices() method once)
    Here are a few original sentences of my assignment which describe what I should do with the MultipleChoiceQuestion class
    Using TrueFalseQuestion as a model, develop a new MultipleChoiceQuestion class that can be used to represent a problem where the user must select one of several answer choices (e.g., "Select answer (a), (b), (c), or (d)."). This new question type should have all of the same externally-visible functionality as TrueFalseQuestion, except that it must:
    maintain a list of potential answer choices
    provide a method that allows the client to construct the list of answer choices one at a time (i.e., the client should be able to call an addAnswerChoice() method to pass a new answer option to the MultipleChoiceQuestion.)
    display (as part of the question text) the list of answer choices with appropriate letters ("abcd" instead of "0123") I don't understand what these sentences mean.
    1. "Maintain a list of potential answer choices"-- this reminds me of the getPossibleAnswerChoice() method in the TrueFalseQuestion class
    public String[] getPossibleAnswerChoice ()
            String[] possibleAnswerChoice = {"true", "false"};
            return possibleAnswerChoice;
        }I wonder that if the potential answer choices I have to store in the MultipleChoiceQuestion class are only letters "a", "b", "c", "d", etc, or include the answer text coming after the letters(eg. a.Red, b.Green)
    2. "provide a method that allows the client to construct the list of answer choices one at a time". How do I achieve the functionality "one at a time"? Do I need to pass the input of the client (a potential answer choice) to the variable of the method which stores the list of potential answers?
    3. "display (as part of the question text) the list of answer choices with appropriate letters". My question here is that: When the client type in one possible answer, should I append it to the variable questionText? (So I use the questionText variable in the methods of the first and second steps)
    Thank you very much for your nice help!
    Edited by: Terry001 on Apr 21, 2008 8:01 AM

  • Dynamic forms in jsf

    Hi all,
    This question has probably been asked a thousand times, but I can't find the answer.
    I am an experienced Struts developer, but now I want to create an application using jsf.
    It will be some kind of quiz with multiple choice questions. The problem is that the number of questions is not fixed, so for 1 quiz there can be 10 questions and for another one 20.
    In struts I know that there is something called map-backed action forms that can be used for this kind of thing.
    Does jsf have something like this? I can't seem to figure it out.
    Thank you.

    There is one thing that I don't like in the example. The generation of components in the backing bean. I am trying to generate them inside my jsp, but it won't work.
    This is the code I use.
    The jsp page
    <body><h:form binding="#{backing_quiz.form1}" id="form1">
            <p>
              <h:dataTable value="#{backing_quiz.questions}" var="question">         
                <h:column>                   
                  <h:outputText value="#{question.questionText}"/>
                  <h:selectOneRadio layout="pageDirection">             
                        <f:selectItems value="#{question.answers}" />                       
                  </h:selectOneRadio>             
                </h:column>
              </h:dataTable>
            </p>
            <p>
              <h:messages/>
            </p>
            <p>
              <h:commandButton value="commandButton1"
                               binding="#{backing_quiz.commandButton1}"
                               id="commandButton1"
                               action="#{backing_quiz.commandButton1_action}"/>
            </p>     
          </h:form></body>The backing bean with session scope.
    public class Quiz {
        private HtmlForm form1;
        private HtmlDataTable dataTable1;
        private HtmlCommandButton commandButton1;
        private ArrayList questions = null;
        private HtmlSelectOneRadio selectOneRadio1;
        private UISelectItem selectItem1;
        private UISelectItem selectItem2;
        private UISelectItem selectItem3;
        public void setForm1(HtmlForm form1) {
            this.form1 = form1;
        public HtmlForm getForm1() {
            return form1;
        public ArrayList getQuestions() {
            if(questions == null) {             
                System.out.println("Create new list");
                questions = new ArrayList();
                Question question = new Question();
                ArrayList answers = new ArrayList();
                answers.add(new SelectItem(1,"vraag 1 antwoord 1"));
                answers.add(new SelectItem(2,"vraag 1 antwoord 2"));
                answers.add(new SelectItem(3,"vraag 1 antwoord 3"));       
                question.setQuestionText("vraag 1");
                question.setAnswers(answers);
                questions.add(question);
                question = new Question();
                answers = new ArrayList();       
                answers.add(new SelectItem(1,"vraag 2 antwoord 1"));
                answers.add(new SelectItem(2,"vraag 2 antwoord 2"));
                answers.add(new SelectItem(3,"vraag 2 antwoord 3"));
                answers.add(new SelectItem(4,"vraag 2 antwoord 4"));
                question.setQuestionText("vraag 2");
                question.setAnswers(answers);
                questions.add(question);
            return questions;
        public void setDataTable1(HtmlDataTable dataTable1) {
            this.dataTable1 = dataTable1;
        public HtmlDataTable getDataTable1() {
            return dataTable1;
        public void setCommandButton1(HtmlCommandButton commandButton1) {
            this.commandButton1 = commandButton1;
        public HtmlCommandButton getCommandButton1() {
            return commandButton1;
        public String commandButton1_action() {
            // Add event code here...
            System.out.println("add item with number " + (((Question)questions.get(0)).getAnswers().size()+1));
            ((Question)questions.get(0)).getAnswers().add(new SelectItem((((Question)questions.get(0)).getAnswers().size()+1) , "Nieuwe vraag " + ((Question)questions.get(0)).getAnswers().size()+1 ));
            return null;
    }The commandButton1_action() needs to add an answer to the first question. This is in fact the backsite where quizes can be created.
    When the action is called an it's redirected to the same page, the answer is added, but due to the fact that the page is rerenderd, the previously selected are gone.
    Is this clear or do I need to give more explanation?

  • Any ideas to cache  records in memory or something?

    HI,
    I have a question about keeping records off the database.
    i have a bean that opens up the recordset puts it in a vector and returns the vector to the jsp from whence it was called.
    But the problem is that these database queries are truly unnecessary. If i could update the recordset say once a month i would be set.
    my QUESTION is does anyone know any strategy for storing the recordset in memory some how ?
    each user might need a different recordset.
    however i could possibly reuse a recordset of about 500 records from Oracle for 1 user but if the user chooses to look at another topic then i would possibly have to refersh that recordset with different info based on a different primary key.

    Thanks.
    QUESTION 1:
    I have been using a Vector to store recordsets.
    The bean method would call a sql statement in another class and loop through the resultset - insert everything as a String into the Vector and return the vector to the JSP page. is that how you would do it?
    Are Vectors serializable? is it possible to implement your solution by caching the Vectors in an HttpSession? or is this restricted to an arraylist
    QUESTION 2:
    You say I should store the arraylist into the HttpSession -
    I just want to double check how you implement this.
    Do you mean that I should have a bean that implements serialiable and instantiate the bean in session scope ?
    with <jsp:useBean id="j" etc etc scope="session" > and everytime the person goes to a page with this instantiation it will just pick it up out of session instead of requerying the db.
    to change the primary key of query in the array list I would pass a different id to the bean and would it automatically know to requery and populate the arraylist?
    Thanks
    Stephen

  • Help With Homework Reading user input into an Array

    This program is to read questions from a file and retrieve user input as answers.
    This program is no where near complete, but I am stuck. (I dont know why, maybe its too late at night)
    I have a total of three classes. I am currently stuck in my main class. See Comments ("What the hell am I printing/ Will this work?"). In this next line of code, i need to read the question from the file to the user, and then accept their input.
    Main Class:
        public static void main(String[] args) {
            try {
            Scanner in = new Scanner(new FileReader("quiz.txt"));
                catch (Exception e) {
                System.out.println(e);
            ArrayList <Questions> Questions = new ArrayList<Questions>();
            ArrayList<String> answers = new ArrayList<String>();
                  for (Questions qu : Questions)
             System.out.println(); //What the hell am I printing.
             String answer = in.nextLine(); //Will this work?
             answers.add(answer); //This should work
          }Questions Class:
    public class Questions {
        String Questions = "";
        public String getQuestions() {
            return Questions;
        public void setQuestions(String Questions) {
            this.Questions = Questions;
        public Questions(String Questions)
            this.Questions = Questions;
    }answers class:
    package QuizRunner;
    * @author Fern
    public class answers {
        String answers = "";
        public String addAnswers() {
            return answers;
        public answers(String answers) {
            this.answers = answers;
        }

    doremifasollatido wrote:
    According to standard Java coding conventions, class names should start with a capital letter (so, your "answers" should be "Answers"). And, variable and method names should start with a lowercase letter (so, your "Questions" should be "questions").
    And classnames should (almost) never be plural words. So it should probably be an 'Answer' and something else containing a collection of those objects called 'answers'.
    Also, *your variable name should not be the same (case-sensitive match) as your class name.* Although it will compile if done syntactically correctly, it is highly confusing! I first wrote this because you did this for both "Questions" and "answers" classes in their class definition, but you also used "Questions" as your variable name in 'main'. (Note that applying the standard capitalization conventions will prevent you from using the same name for your class name as for your variable name, since they should start with different cases.)
    Of course having an 'Answer' called 'answer' is often fine.
    Your Questions class should probably be called "Question", anyway--it looks like it should hold a single question. And, your "answers" class should probably be called "Answer"--it looks like it should hold a single answer. You aren't using your "answers" class anywhere right now, anyway.Correct. There might be room for a class containing a collection of Question objects, but it's unlikely such a class would contain just that and nothing else.

  • Question | Using JSTL to Display elements of an ArrayList of HashMaps

    Hi All,
    I would like some advice on the following code snippet which is a representation of my real code. Please see below for the code snippet and the specific questions I have.
    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
    <%
    // This Object is an ArrayList of HashMaps
    MyClassDataBean myDb =  (MyClassDataBean)session.getAttribute("testDataBean");
    // Adding myDb to the pageContext so that EL can be used to render components in this Object
    pageContext.setAttribute("myDb",myDb);
    pageContext.setAttribute("column1",MyConstants.COLUMN1);
    pageContext.setAttribute("column2",MyConstants.COLUMN2);
    %>
    <html>
    <head></head>
    <body>
         <c:choose>
          <c:when test="${myDb != null}" >
             <c:forEach var="hashMapAsRow" items="${myDb}" varStatus="lineInfo">
              <tr>
                  <td><c:out value="${hashMapAsRow[column1]}" /></td>
               <td><c:out value="${hashMapAsRow[column2]}" /></td>
               </tr>
         </c:forEach>
         </c:when>
         <c:otherwise>
         <tr><td colspan="100%">No Data Exists</td></tr>
         </c:otherwise>
       </c:choose>
    </body>
    </html>Question: Is there an alternative to accessing elements using the core tag library in this Object without using pageContext.setAttribute() ? If not, would the c_rt library be better to use in this scenario? If so, could someone give me an example of the right way to use it based on the above example?
    Thanks,
    Joe

    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
    <c:set var="myDb"  value="${sessionScope.testDataBean}" />
    <html>
    <head></head>
    <body>
          <c:choose>
           <c:when test="${myDb != null}" >
              <c:forEach var="hashMapAsRow" items="${myDb}" varStatus="lineInfo">
               <tr>
                   <td><c:out value="${hashMapAsRow['column1']}" /></td>
                 <td><c:out value="${hashMapAsRow['column2']}" /></td>
                </tr>
         </c:forEach>
          </c:when>
          <c:otherwise>
         <tr><td colspan="100%">No Data Exists</td></tr>
          </c:otherwise>
        </c:choose>
    </body>
    </html> or the one below
    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
    <html>
    <head></head>
    <body>
          <c:choose>
           <c:when test="${sessionScope.testDataBean != null}" >
              <c:forEach var="hashMapAsRow" items="${sessionScope.testDataBean}" varStatus="lineInfo">
               <tr>
                   <td><c:out value="${hashMapAsRow['column1']}" /></td>
                 <td><c:out value="${hashMapAsRow['column2']}" /></td>
                </tr>
         </c:forEach>
          </c:when>
          <c:otherwise>
         <tr><td colspan="100%">No Data Exists</td></tr>
          </c:otherwise>
        </c:choose>
    </body>
    </html> is this the one which you are looking for ??
    REGARDS,
    RaHuL

  • Novice question: ArrayList error

    Two classes: Bank and Customer.
    Customer class has this constructor:
    public class Customer {
    protected String cust_name;
    protected int card_number;
    protected double current_bal;
    protected double credit_limit;
    public Customer(String ID, int CCN, double balance, double limit) {
    cust_name = ID;
    card_number =  CCN;
    current_bal = balance;
    credit_limit = limit;
    }Bank class has an ArrayList of Customer objects.
    import java.util.ArrayList;
    public class Bank extends Customer
    ArrayList<Customer> customers = new ArrayList<Customer>();
    /* here is the error on below line: compiler outputs "<identifier> expected"
    customers.add(new Customer("Nicholas Cage", 345, 225.0, 2600.0));Is it wanting an identifier in the add method? (i.e. customers.add(1, new Customer....)

    customer object being added to the arraylist is fine..u should have the customers.add() within a method...where you have that customers.add()?
    if its within a methed then just verify if the braces above are closed properly b'coz this error might come if the braces are not closed properly..

  • Questions on filtering and sorting an arraylist

    Hello All,
    I'm trying to figure out a better way to do this code, but what I'm doing is taking an arrayList and filtering it using iter.remove(), based on a criteria I have, then take the results and sort them. The code below works, but I was seeing class cast exceptions when I tried to do a ss.addAll(list);
    , but it worked when I just added the set object. Why is this and is there a better way to do all this?
    Set set = new HashSet();
    List retList = new ArrayList();
    SortedSet ss = new TreeSet();
    for(Iterator iter = list.iterator(); iter.hasNext();){
    .//More code...
    iter.remove();
    //Remove duplicates.
    set.addAll(list);
    ss.add(set);
    retList.addAll(set);
    return retList;

    Your current code is adding the set (the hash set) as one element (the only element?) of the sorted set. Is this what you want to do? Would you rather add each element of the set to the sorted set?
    I don't know about the class cast exceptions. If you want somebody's comment on this part, you may consider posting code and stack trace.
    I think I'd rely on Collections.sort() for sorting rather than TreeSet. If you prefer TreeSet, why not skip the hash set in between?
    Hope this helps.
    Please remember the code button/tags.

  • Question on import java.util.ArrayList, etc.

    Hi,
    I was wondering what the following meant and what the differences were. When would I have to use these:
    import java.util.ArrayList;
    import java.util.Collections; <--I especially don't understand what this means
    import java.util.Comparator; <---same for this (can I consolidate these into the bottom two?)
    import java.io.*;
    import java.util.*;

    MAresJonson wrote:
    Also, what does this mean:
    return foo == f.getFoo() ? true : false;
    (more specifically...what does the "? true : false" mean and is there another way to code that?)It's called the ternary operator. For your specific example, you could just do:
    return foo == f.getFoo();But, more generally,
      return foo == f.getFoo() ? "equal" : "Not equal";means:
    if (foo == f.getFoo()) {
       return "equal";
    else {
       return "Not equal";
    }As everyone else said at the same time...

  • ArrayList, the same old newbie questions..

    I get this:
    Exception in thread "main" java.lang.NoClassDefFoundError: ArrayLists/java
    When trying to run a good friend of mine 's code:
    import java.util.*;
    /** Browser history class. This class functions
    * linearly, to store and get all names.
    class BrowserHistory
         private ArrayList backHistory, forwardHistory;
         private Object currentPage = "";
         public BrowserHistory()
              backHistory = new ArrayList();
              forwardHistory = new ArrayList();
         public void newURL(String url)
              if (currentPage.equals(null) || currentPage.equals(""))
                   //Do nothing
              else
                   backHistory.add(0,currentPage);
              currentPage = url;
              forwardHistory.clear();
         public String forward()
              backHistory.add(0,currentPage);
              currentPage = forwardHistory.get(0);
              forwardHistory.remove(0);
              return (String)currentPage;
         public String back()
              forwardHistory.add(0,currentPage);
              currentPage = backHistory.get(0);
              backHistory.remove(0);
              return (String)currentPage;
         public boolean backIsEmpty()
              return backHistory.isEmpty();
         public boolean forwardIsEmpty()
              return forwardHistory.isEmpty();
    Instantiation of the ArrayList class seems to be the problem, but I can't find a solution.

    There can be only 2 problems with this:
    1.) Your classpath is incorrect.Probable.
    2.) Your JDK version is old and does not contain the
    Collection framework classes.JDK V. 1.4.
    Thanks a lot, Vikas.
    Vikas

  • Help with ArrayList...

    Hi Everyone:
    I have this java program that I'm doing for school and I need a little bit of insite on how to do certain things. Basically what I did was I read a text file into the program. Once I tokenized the text(by line), I created another object(we'll call it Throttle) and passed the values that was tokenized, then I stored the object(Throttle) into ArrayList. Now, my question is how to I access the object(Throttle) from the ArrayList and use the object's(Throttle) methods? Here's the code that I have currently:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    public class Project1 extends JFrame
    private JButton numOfThrottles, shiftThrottle, createThrottle, quit;
    private JPanel panel;
    private FileReader fr;
    private BufferedReader br;
    private FileWriter fw;
    private int tempTop;
    private int whatToShift;
    private int tempPosition;
    private ArrayList arrThrottles = new ArrayList();
    private String line;
    private Throttle myThrottle = null, daThrottle;
    private StringTokenizer st;
    public Project1()
    super ("Throttles - by Joe Munoz");
    panel = new JPanel();
    setContentPane(panel);
    panel.setLayout(null);
    //**button stuff
    numOfThrottles = new JButton("Number of Throttles");
    shiftThrottle = new JButton("Shift a Throttle");
    createThrottle = new JButton("Create New Throttle");
    quit = new JButton("Quit");
    panel.add(numOfThrottles);
    panel.add(shiftThrottle);
    panel.add(createThrottle);
    panel.add(quit);
    numOfThrottles.setBounds(5,7,150,25);
    shiftThrottle.setBounds(5,30,150,25);
    createThrottle.setBounds(5,50,150,25);
    quit.setBounds(5,70,150,25);
    numOfThrottles.addActionListener(new ClickDetector());
    shiftThrottle.addActionListener(new ClickDetector());
    createThrottle.addActionListener(new ClickDetector());
    quit.addActionListener(new ClickDetector());
    //window stuff
    setSize(170,135);
    show();
    try
    br = new BufferedReader(new FileReader("C:\\Storage.txt"));
    catch (FileNotFoundException ex)
    System.out.println ("File Not Found!");
    try
    line = br.readLine();
    while (line != null)
    st = new StringTokenizer(line, " ");
    tempTop = Integer.parseInt(st.nextToken());
    tempPosition = Integer.parseInt(st.nextToken());
    myThrottle = new Throttle(tempTop, tempPosition);
    arrThrottles.add(myThrottle);
    line = br.readLine();
    catch(Exception e)
    System.out.println("IO Exception!!!");
    System.exit(0);
    private class ClickDetector implements ActionListener
    public void actionPerformed(ActionEvent event)
    try
    if (event.getSource() == numOfThrottles)
    JOptionPane.showMessageDialog(null, "Number of Throttles is..." + myThrottle.getNumOfThrottles());
    if (event.getSource() == shiftThrottle)
    String shift = JOptionPane.showInputDialog("Please Choose a Throttle from 0 to " + (arrThrottles.size() - 1));
    whatToShift = Integer.parseInt(shift);
    System.out.println ("whatToShift = " + whatToShift);
    // Need help here
    if (event.getSource() == createThrottle)
    String inTop = JOptionPane.showInputDialog("Please Enter Top");
    tempTop = Integer.parseInt(inTop);
    String inPosition = JOptionPane.showInputDialog("Please Enter Position");
    tempPosition = Integer.parseInt(inPosition);
    myThrottle = new Throttle(tempTop, tempPosition);
    arrThrottles.add(myThrottle);
    JOptionPane.showMessageDialog(null, "The Throttle has been created");
    if (event.getSource() == quit)
    System.out.println ("you clicked quit");
    catch (Exception e)
    JOptionPane.showMessageDialog(null, "No Numbers inputted!");
    Any insite/suggestions on what to do? Thank You.
    Joe

    Hi,
    I have a question addition to this same question.
    If you have an object and there are 10 different objects with in the object ..
    tempTop = Integer.parseInt(st.nextToken());
    tempPosition = Integer.parseInt(st.nextToken());
    tempBottom = 10;
    Is this how you access( from the same example) each object value
    strTop= (Throttle)arrThrottles.get(i).tempTop;
    strPos= (Throttle)arrThrottles.get(i).tempPosition;
    strB= (Throttle)arrThrottles.get(i).tempBottom;
    ----I AM USING ARRAYS in a JAVABEAN
    Class test {
    public objectTEMP t[] = null;
    public void initialize(val1,al2) {
         t = redim(t,10,false); //To set the length of the array to 10
    public class T {
    String s1 = null;
    String s2 = null;
    int i1 = null;
    public void setS1(String inVal) {
              s1=inVal;
    public void setS2(String inVal) {
         s2=inVal;
    public void setI1(int inVal) {
         i1=inVal;
    public String getS1() {
              return s1;
    public String getS2() {
              return s2;
    public String getI1() {
              return i1;
    for (int i=0; i<t.length;i++) {
    System.out.println("t"+i+t.getS1());
    t.setS1("SOMESTRING");
    System.out.println("t"+i+t.getS1());
    Any use the setter and getter method from JSP to update or get the information.
    I want to change this to ArrayList as they are fast and they have resizing ability.
    How to I implement this in ARRAYLIST.
    Thanks a bunch

  • Huge headache, ArrayList from Txt File

    I'm trying to generate an ArrayList from a text file. But the problem is I have no idea how to go about it properly. This is what I've gotten so far.
    import java.io.*;
    import java.util.*;
    public class reader
              try
                   FileReader input = new FileReader("quizscore.txt");
                   BufferedReader bufferInput = new BufferedReader(input);
                   String line;
                   while ((line = bufferInput.readLine ()) !=null )
                   String[] result = line.split("\\s");
                   for (int x=0; x<result.length; x++)
                        System.out.println(result[x]);
              catch (IOException e)
                   System.out.println("Error:" + e);
    }That is my data reader which is reading a text file with a buncha numbers like this,
    9893 034 009 077 078 020
    1947 045 040 088 078 055
    2877 055 050 099 078 080
    3189 022 070 100 078 077
    Now I want to create an ArrayList to put all that data into. I cannot seem to set it up correctly and it's driving me nuts.
    class Student
         public int idNum;
         public int quiz1;
         public int quiz2;
         public int quiz3;
         public int quiz4;
         public int quiz5;
         public Student(int id, int q1, int q2, int q3, int q4, int q5)
              this.idNum = id;
              this.quiz1 = q1;
              this.quiz2 = q2;
              this.quiz3 = q3;
              this.quiz4 = q4;
              this.quiz5 = q5;
    }Now where would I put the
    ArrayList StudentData = new ArrayList();
    so that when I read the text file, it automatically writes into the ArrayList formated like the public Student object I have? I was orginally supposed to use the StringTokenizer but after reading the java documentation it suggested I code using the split function. So the question is, how do I get it to write every line's tokens into one array row and so on?

    Using turng's code as a sort of guideline, I have created this piece of code. There are some problems though. The array doesn't seem to be writing properly.
    import java.io.*;
    import java.util.*;
    public class getData
         public getData()
         public void load(File file)
              String[][] studentData = new String[40][6];
              try
                   FileReader input = new FileReader(file);
                   BufferedReader bufferInput = new BufferedReader(input);
                   String line;
                   while ((line = bufferInput.readLine ()) !=null )
                   System.out.println(line);
                   //String[] result = line.split("\\s");
                   //for (int x=0; x<result.length; x++)
                   //     System.out.println(result[x]);
                   for (int l = 0; l <40; l++)
                             for (int i = 0; i < 6; i++)
                                  String[] tokens = line.split("\\s");
                                  for (int x = 0; x<tokens.length; x++)
                                       studentData[l] = tokens[x];
                                       System.out.println("L is:" + l);
                                       //System.out.print("I is:" + i);
                                       System.out.println(studentData[l][i]);
              catch (IOException e)
                   System.out.println("Error:" + e);
         public static void main(String arg[])
              (new getData()).load(new File("quizscore.txt"));
    Basically what happens when I run through this, it prints this (This is the last portion, I'm assuming it goes from 0-39)
    L is:38
    6999
    L is:38
    000
    L is:38
    098
    L is:38
    089
    L is:38
    078
    L is:38
    020
    L is:38
    6999
    L is:38
    000
    L is:38
    098
    L is:38
    089
    L is:38
    078
    L is:38
    020
    L is:38
    6999
    L is:38
    000
    L is:38
    098
    L is:38
    089
    L is:38
    078
    L is:38
    020
    L is:38
    6999
    L is:38
    000
    L is:38
    098
    L is:38
    089
    L is:38
    078
    L is:38
    020
    L is:38
    6999
    L is:38
    000
    L is:38
    098
    L is:38
    089
    L is:38
    078
    L is:38
    020
    L is:38
    6999
    L is:38
    000
    L is:38
    098
    L is:38
    089
    L is:38
    078
    L is:38
    020
    L is:39
    6999
    L is:39
    000
    L is:39
    098
    L is:39
    089
    L is:39
    078
    L is:39
    020
    L is:39
    6999
    L is:39
    000
    L is:39
    098
    L is:39
    089
    L is:39
    078
    L is:39
    020
    L is:39
    6999
    L is:39
    000
    L is:39
    098
    L is:39
    089
    L is:39
    078
    L is:39
    020
    L is:39
    6999
    L is:39
    000
    L is:39
    098
    L is:39
    089
    L is:39
    078
    L is:39
    020
    L is:39
    6999
    L is:39
    000
    L is:39
    098
    L is:39
    089
    L is:39
    078
    L is:39
    020
    L is:39
    6999
    L is:39
    000
    L is:39
    098
    L is:39
    089
    L is:39
    078
    L is:39
    020The actual text file that is being read,
    Stud Qu1 Qu2 Qu3 Qu4 Qu5
    1234 052 007 100 078 034
    2134 090 036 090 077 030
    3124 100 045 020 090 070
    4532 011 017 081 032 077
    5678 020 012 045 078 034
    6134 034 080 055 078 045
    7874 060 100 056 078 078
    8026 070 010 066 078 056
    9893 034 009 077 078 020
    1947 045 040 088 078 055
    2877 055 050 099 078 080
    3189 022 070 100 078 077
    4602 089 050 091 078 060
    5405 011 011 000 078 010
    6999 000 098 089 078 020It's writing the very last line throughout the whole array. Why is this? I know my loop coding is probably the problem, and I'm trying to draw out the flow on a piece of paper, but it's confusing me more and more. And I do apologize in advance if the error that's causing this is some simple coding error I should have learned before but probably haven't.
    Edited by: soulesschild on Nov 16, 2007 5:39 PM

Maybe you are looking for

  • What login name do I need to use for iCloud?

    I'm operating on Windows 7 64bit. I just installed iCloud and it prompted me to "Sign in with my Apple ID:" which I did. Then I get this: "This Apple ID is valid but is not an iCloud account" - I am using a gmail address. What domain do I need to be

  • Select Single * is not fetching all Data

    Hi, I have a peculiar problem, when i am extending the customer to a new company code, we are getting Dump saying 'ASSERTION_FAILED' when i debugg i am geeting issue with following Code of a FM 'KNA1_SINGLE_READER' IF NOT i_bypassing_buffer IS INITIA

  • Can't import into Vista

    Hi! I have had a problem with iTunes for three months now. Argh! I am having trouble importing cds and having them actually work in my library. When the songs are done "importing" the end time is listed as 789:00:00 or something like that. (They won'

  • Cannot open Message Catalog CMDTUX_CAT

    Hi. I've just installed Tuxedo for Redhat 6.2, and I'm trying to set it up, and I'm stuck with 'simpapp'. I have this struct: TUXDIR=/home/bea/tuxedo8.0 APPDIR=/applications/simpapp when I run tmloadcf ubbsimple i get this error: NLS:4: Cannot open m

  • PDF in qualifier fields ?

    Hi, all I have a PDF lookup field in qualified table as a qualifier. When I select it and click 'View PDF..." system doesn't react and when i click 'Edit externally' or 'Save PDF' I get errors like 'Data Table Not Found, Version SP5 (5.5.42.65)' and