Results 1 to 9 of 9
  1. #1
    saytri is offline Member
    Join Date
    Dec 2007
    Posts
    34
    Rep Power
    0

    Default Pls help with a problem.

    I'm making a quiz, and i store the questions in a textfile. The user can choose from 3 quizes, either Plate Tectonics, Rivers or Rocks. I managed to call the questions from Java. Each quiz has a set of 10 questions. In the code below i only included the answers to the Plate Tectonics Quiz, which i stored in an array. What i'm having problem with is, that its not working correctly, since it is displaying, after answering all the questions correctly that i have answered 0 questions from 1 question. First of all it should say out of 10 questions because i have 10 questions, and its not really working because even if i answer them all corrctly it still says 0 out of 1 question. Can someone pls help me find the error? Thanks a lot.


    this is the code i have written:

    Java Code:
    import javax.swing.*;
    
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    
    import java.io.*;
    
    import java.util.Scanner;
    import java.util.Arrays;
    
    public class GeographyQuiz extends JFrame implements ActionListener {
    
      private static final int FRAME_WIDTH = 140;
      private static final int FRAME_HEIGHT = 160;
      private static final int FRAME_X_ORIGIN = 70;
      private static final int FRAME_Y_ORIGIN = 50;
    
       AnswerStore answerStore = new AnswerStore();
      
      public static void main (String[] args) {
    
        JFrame jFrame;
        jFrame = new JFrame();
    
        JOptionPane.showMessageDialog(jFrame, "This is a Geography Quiz");
        JOptionPane.showMessageDialog(null, "Good Luck");
    
        char choice;
        int i, choice1, Password;
        String yourChoice, passString;
    
        passString = JOptionPane.showInputDialog("Enter the Password");
    
        //Password = passString.nextInt();
        Password = Integer.parseInt(passString);
    
        if (Password == 123) {
         JOptionPane.showMessageDialog(null, "Valid. You typed the right password. Now choose from the following menu");
    
         GeographyQuiz frame = new GeographyQuiz();
          frame.setVisible(true);
    
        } else {
          JOptionPane.showMessageDialog(null, "Invalid Password. Try Again");
        }
      }
    
      public GeographyQuiz() {
        Container contentPane;
        JButton button1, button2, button3, button4, button5;
    
        setSize (FRAME_WIDTH, FRAME_HEIGHT);
        setTitle("Geography Quiz");
        setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
    
        contentPane = getContentPane();
        contentPane.setBackground(Color.pink);
        contentPane.setLayout(new FlowLayout());
    
        button1 = new JButton("Plate Tectonics");
        button2 = new JButton("Rivers");
        button3 = new JButton("Rocks");
        button4 = new JButton("Quit");
    
        contentPane.add(button1);
        contentPane.add(button2);
        contentPane.add(button3);
        contentPane.add(button4);
        
        button1.addActionListener(this);
        button1.setActionCommand("b1");
        button2.addActionListener(this);
        button2.setActionCommand("b2");
        button3.addActionListener(this);
        button3.setActionCommand("b3");
        button4.addActionListener(this);
        button4.setActionCommand("b4");
    
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    
      } 
      
       public void actionPerformed(ActionEvent e) {
     String ac = e.getActionCommand();
            String[] questions = null;
             try {
            
            if (ac.equals("b1")) {
                questions = readFile("plate_tectonics.txt");
            } else if(ac.equals("b2")) {
                questions = readFile("rivers.txt");
            } else if(ac.equals("b3")) {
                questions = readFile("rocks.txt");
            } else if (ac.equals("b4")) {
                System.exit(0);
            }
            askQuestions(questions);
        }
         
         catch (java.io.FileNotFoundException f)
    {
            JOptionPane.showMessageDialog(null, "File not found.");
        
        }
    }
        
          
         
    
        private String[] readFile(String path)throws FileNotFoundException {
            Scanner s = null;
            StringBuilder sb = new StringBuilder();
            String separator = "\n";
            try {
                s = new Scanner(new BufferedReader(new FileReader(path)));
                s.useDelimiter(",\\s*");
                while (s.hasNext()) {
                   
                   JOptionPane.showInputDialog(null,s.nextLine());
                }
            }
            finally {
                if (s != null) 
                    s.close();
                
            }
            return sb.toString().split("\\s");
        }
    
        private void askQuestions(String[] questions) {
            int count = 0;
           
            for(int j = 0; j < questions.length; j++) {
                 
                 String input = JOptionPane.showInputDialog(null, questions[j]);
                 // Use reference to AnswerStore instance to access data in it.
                 if(answerStore.answer[j].equals(input))
    
                 count++;
            }
            JOptionPane.showMessageDialog(null, "You answered " + count +
                                          " out of " + questions.length +
                                          " questions correctly.");
        }
    }
    
    class AnswerStore  {
      
    String[] answer = {
            "Hellenic", "constructive", "100km", "Italy", "Wegner",
            "constructive", "100km", "Italy", "destroyed", "Meditteranean"
        };
    }
    Thanks a lot for the help. I appreciate it a lot. :)
    Last edited by saytri; 12-23-2007 at 11:43 AM.

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    it is displaying, after answering all the questions correctly that i have answered 0 questions from 1 question
    Right away we would suspect trouble int the askQuestions method. This is one of the benefits of encapsulating your code into methods according to function/what_you_are_doing.
    The general idea is to investigate in the area of suspected trouble.
    Pseudo code suggestions:
    Java Code:
        private void askQuestions(String[] questions) {
            // What is being passed into this method? You can check the
            // length or the data of the "questions" array.
            System.out.printf("questions = %s%n", Arrays.toString(questions));
            int count = 0;
            for(int j = 0; j < questions.length; j++) {
                 String input = JOptionPane.showInputDialog(null, questions[j]);
                 // Sounds like the "count" variable is not incrementing
                 // so we may have trouble with this [i]if[/i] statement.
                 // Let's have a look:
                 System.out.printf("answerStore.answers[%d].equals(%s) = %b%n",
                                    j, input, answerStore.answers[j].equals(input));
                 if(answerStore.answers[j].equals(input))
                     count++;
            }
            JOptionPane.showMessageDialog(null, "You answered " + count +
                                          " out of " + questions.length +
                                          " questions correctly.");
        }
    Sometimes String input may need to be trimmed or examined/adjusted for case. You have to keep checking for the details of what is being used in the logic test(s) until you find what is off.

  3. #3
    saytri is offline Member
    Join Date
    Dec 2007
    Posts
    34
    Rep Power
    0

    Default

    Yeah i see your point. And i knew that the problem was somewhere there. But i cannot understand why because i think that it should work correctly since it is comparing the answer stored(correct answer) to the one entered by the user. And then it increments the counter. And i think thats what the program should do. By the way thanks alot for your help. I really appreciate it.

    Its displaying this now:

    questions = []
    answerStore.answers[0].equals() = false

    Thanks again. :-)

  4. #4
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    Java Code:
    questions = []
    So the method is receiving an empty array. This points back to the method that is reading the file. We need to start investigating what is happening in the readFile method.

  5. #5
    saytri is offline Member
    Join Date
    Dec 2007
    Posts
    34
    Rep Power
    0

    Default

    I'm really sorry if i'm bothering you, but i really can't find where's the problem. Because the program is reading the file correctly, it seems that the count is not working because its not incrementing. I'm still a beginner in java, and such errors are a bit difficult to find. Thanks a lot for helping me out, i really appreciate your help. :-)

  6. #6
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    Without seeing the file you are trying to read I have no idea what might be going awry. How your files are written and how you attempt to read them plays a big part in what you get from the readFiles method. I made up a text file with ten lines in it and read it for the plate tectonics quiz. Typing in the answers from the AnswerStore.answers string array worked okay.
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    
    public class GQ extends JFrame implements ActionListener {
        private static final int FRAME_WIDTH = 140;
        private static final int FRAME_HEIGHT = 160;
        private static final int FRAME_X_ORIGIN = 70;
        private static final int FRAME_Y_ORIGIN = 50;
        AnswerStore answerStore = new AnswerStore();
    
        public static void main (String[] args) {
            JOptionPane.showMessageDialog(null, "This is a Geography Quiz");
            JOptionPane.showMessageDialog(null, "Good Luck");
    
            String passString = JOptionPane.showInputDialog("Enter the Password");
    
            //Password = passString.nextInt();
            int Password = Integer.parseInt(passString.trim());
    
            if (Password == 123) {
                JOptionPane.showMessageDialog(null, "Valid. You typed the right password. " +
                                              "Now choose from the following menu");
    
                GQ frame = new GQ();
                frame.setVisible(true);
            } else {
                JOptionPane.showMessageDialog(null, "Invalid Password. Try Again");
            }
        }
    
        public GQ() {
            Container contentPane;
            JButton button1, button2, button3, button4, button5;
    
            setSize (FRAME_WIDTH, FRAME_HEIGHT);
            setTitle("Geography Quiz");
            setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
    
            contentPane = getContentPane();
            contentPane.setBackground(Color.pink);
            contentPane.setLayout(new FlowLayout());
    
            button1 = new JButton("Plate Tectonics");
            button2 = new JButton("Rivers");
            button3 = new JButton("Rocks");
            button4 = new JButton("Quit");
    
            contentPane.add(button1);
            contentPane.add(button2);
            contentPane.add(button3);
            contentPane.add(button4);
        
            button1.addActionListener(this);
            button1.setActionCommand("b1");
            button2.addActionListener(this);
            button2.setActionCommand("b2");
            button3.addActionListener(this);
            button3.setActionCommand("b3");
            button4.addActionListener(this);
            button4.setActionCommand("b4");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        }
      
        public void actionPerformed(ActionEvent e) {
            String ac = e.getActionCommand();
            String[] questions = null;
            if (ac.equals("b1")) {
                questions = readFile("plate_tectonics.txt");
            } else if(ac.equals("b2")) {
                questions = readFile("rivers.txt");
            } else if(ac.equals("b3")) {
                questions = readFile("rocks.txt");
            } else if (ac.equals("b4")) {
                System.exit(0);
            }
            askQuestions(questions);
        }
    
        private String[] readFile(String path) {
            Scanner s = null;
            StringBuilder sb = new StringBuilder();
            String separator = "\n";
            try {
                s = new Scanner(new BufferedReader(new FileReader(path)));
    //            s.useDelimiter(",\\s*");
                while (s.hasNext()) {
                    sb.append(s.nextLine() + separator);
    //                JOptionPane.showMessageDialog(null,s.next());
                }
            } catch(IOException e) {
                System.out.println("read error: " + e.getMessage());
            } finally {
                if (s != null) 
                    s.close();
    //            break;
            }
            // What did we get?
            System.out.println("sb = " + sb.toString());
            System.out.printf("sb.split = %s%n", Arrays.toString(sb.toString().split("\\n")));
            return sb.toString().split("\\n");
        }
    
        private void askQuestions(String[] questions) {
            System.out.printf("questions = %s%n", Arrays.toString(questions));
            int count = 0;
            for(int j = 0; j < questions.length; j++) {
                 String input = JOptionPane.showInputDialog(null, questions[j]);
                 if(answerStore.answers[j].equals(input))
                     count++;
            }
            JOptionPane.showMessageDialog(null, "You answered " + count +
                                          " out of " + questions.length +
                                          " questions correctly.");
        }
    }
    
    class AnswerStore  {
        String[] answers = {
            "Hellenic", "constructive", "100km", "Italy", "Wegner",
            "constructive", "100km", "Italy", "destroyed", "Mediterranean"
        };
    }
    plate_tectonics.txt
    Java Code:
    Question 1
    Question 2
    Question 3
    Question 4
    Question 5
    Question 6
    Question 7
    Question 8
    Question 9
    Question 10

  7. #7
    saytri is offline Member
    Join Date
    Dec 2007
    Posts
    34
    Rep Power
    0

    Default Help with a for loop

    Hey thanks a lot. It has worked now. You are totally Awesome. And thanks a lot for your help. Btw Happy Christmas and a Happy New Year. Thanks again. :-)

    Now i did the same for the other 2 quizzes. But i have this problem because after responding for example to the plate tectonics quiz and it tells me how many correct answers i responded it is displaying the questions again. Do i have to do seperate methods for each quiz so that, the askQuestions method will not have to loop 3 times?


    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    
    public class GQ extends JFrame implements ActionListener {
        private static final int FRAME_WIDTH = 140;
        private static final int FRAME_HEIGHT = 160;
        private static final int FRAME_X_ORIGIN = 70;
        private static final int FRAME_Y_ORIGIN = 50;
        AnswerStore answerStore = new AnswerStore();
    
        public static void main (String[] args) {
            JOptionPane.showMessageDialog(null, "This is a Geography Quiz");
            JOptionPane.showMessageDialog(null, "Good Luck");
    
            String passString = JOptionPane.showInputDialog("Enter the Password");
    
            //Password = passString.nextInt();
            int Password = Integer.parseInt(passString.trim());
    
            if (Password == 123) {
                JOptionPane.showMessageDialog(null, "Valid. You typed the right password. " +
                                              "Now choose from the following menu");
    
                GQ frame = new GQ();
                frame.setVisible(true);
            } else {
                JOptionPane.showMessageDialog(null, "Invalid Password. Try Again");
            }
        }
    
        public GQ() {
            Container contentPane;
            JButton button1, button2, button3, button4, button5;
    
            setSize (FRAME_WIDTH, FRAME_HEIGHT);
            setTitle("Geography Quiz");
            setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
    
            contentPane = getContentPane();
            contentPane.setBackground(Color.pink);
            contentPane.setLayout(new FlowLayout());
    
            button1 = new JButton("Plate Tectonics");
            button2 = new JButton("Rivers");
            button3 = new JButton("Rocks");
            button4 = new JButton("Quit");
    
            contentPane.add(button1);
            contentPane.add(button2);
            contentPane.add(button3);
            contentPane.add(button4);
        
            button1.addActionListener(this);
            button1.setActionCommand("b1");
            button2.addActionListener(this);
            button2.setActionCommand("b2");
            button3.addActionListener(this);
            button3.setActionCommand("b3");
            button4.addActionListener(this);
            button4.setActionCommand("b4");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        }
      
        public void actionPerformed(ActionEvent e) {
            String ac = e.getActionCommand();
            String[] questions = null;
            if (ac.equals("b1")) {
                questions = readFile("plate_tectonics.txt");
            } else if(ac.equals("b2")) {
                questions = readFile("rivers.txt");
            } else if(ac.equals("b3")) {
                questions = readFile("rocks.txt");
            } else if (ac.equals("b4")) {
                System.exit(0);
            }
            askQuestions(questions);
        }
    
        private String[] readFile(String path) {
            Scanner s = null;
            StringBuilder sb = new StringBuilder();
            String separator = "\n";
            try {
                s = new Scanner(new BufferedReader(new FileReader(path)));
    //            s.useDelimiter(",\\s*");
                while (s.hasNext()) {
                    sb.append(s.nextLine() + separator);
    //                JOptionPane.showMessageDialog(null,s.next());
                }
            } catch(IOException e) {
                System.out.println("read error: " + e.getMessage());
            } finally {
                if (s != null) 
                    s.close();
    //            break;
            }
            // What did we get?
            System.out.println("sb = " + sb.toString());
            System.out.printf("sb.split = &#37;s%n", Arrays.toString(sb.toString().split("\\n")));
            return sb.toString().split("\\n");
        }
    
        private void askQuestions(String[] questions) {
            System.out.printf("questions = %s%n", Arrays.toString(questions));
            int count = 0;
            for(int j = 0; j < questions.length; j++) {
                 String input = JOptionPane.showInputDialog(null, questions[j]);
                 if(answerStore.answers[j].equals(input))
                     count++;
                     
                    }
                     JOptionPane.showMessageDialog(null, "You answered " + count +
                                          " out of " + questions.length +
                                          " questions correctly.");
                                      
               for(int i = 0; i < questions.length; i++) {
                 String input = JOptionPane.showInputDialog(null, questions[i]);
                 if(answerStore.answers[i].equals(input))
                     count++;
                     
                    }
                     JOptionPane.showMessageDialog(null, "You answered " + count +
                                          " out of " + questions.length +
                                          " questions correctly.");
                    
                 for(int k = 0; k < questions.length; k++) {
                 String input = JOptionPane.showInputDialog(null, questions[k]);
                 if(answerStore.answers[k].equals(input))
                     count++;
                     
                    }
                     JOptionPane.showMessageDialog(null, "You answered " + count +
                                          " out of " + questions.length +
                                          " questions correctly.");
            
        }
    }
    
    class AnswerStore  {
        String[] answers = {
            "Hellenic", "destructive", "100km", "Italy", "Wegner",
            "Mariana", "Sicily", "created", "constructive", "Mediterranean"
        };
        
        String[] answersri = {
            "Hello", "mulley", "c", "d", "e",
            "f", "Sicily", "created", "constructive", "Mediterranean"
        };
        
        String[] answersro = {
            "heavy", "mini", "a", "b", "Wegner",
            "Mariana", "Sicily", "created", "constructive", "Mediterranean"
        };
    
    
      }
    Last edited by saytri; 12-24-2007 at 06:43 PM.

  8. #8
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    it is displaying the questions again
    You added two more loops of the same question_and_answer code inside the askQuestions method. You only need one. Stand back and look at the flow of your application. The user selects a quiz via a button in your gui. The button ActionListener receives the event (in actionPerformed) sent by the button, determines which button was selected by the user and then sends the corresponding file name off to the readFile method for the method to read the file and send back a String array of the questions. Then the ActionListener sends the array of questions off to the askQuestions method for it to ask each one to the user and receive the users response/answer, compare them with the AnswerStore answers and inform the user how well they did. Then we wait for the user to select another quiz and it all happens again...
    The new part is that we need to match up the questions and answers. In pseudo java:
    Java Code:
        public void actionPerformed(ActionEvent e) {
            String ac = e.getActionCommand();
            String[] questions = null;
            String[] answers = null;
            if (ac.equals("b1")) {
                questions = readFile("plate_tectonics.txt");
                // You can be creative with your variable names.
                // Think of another person seeing this for the
                // first time. The names you use might contribute
                // to helping them understand the structure,
                // logic and flow of your program.
                answers = answerStore.tectonicAnswers;
            } else if(ac.equals("b2")) {
                questions = readFile("rivers.txt");
                answers = answerStore.riverAnswers;
            } else if(ac.equals("b3")) {
                questions = readFile("rocks.txt");
                answers = answerStore.rockAnswers;
            } else if (ac.equals("b4")) {
                System.exit(0);
            }
            askQuestions(questions, answers);
        }
    
        private void askQuestions(String[] questions, String[] answers) {
            // Just for debugging. Remove this from your final code.
            System.out.printf("questions = %s%nanswers = %s%n",
                               Arrays.toString(questions),
                               Arrays.toString(answers));
            int count = 0;
            for(int j = 0; j < questions.length; j++) {
                String input = JOptionPane.showInputDialog(null, questions[j]);
                if(answers[j].equals(input))
                    count++;
                     
                }
                JOptionPane.showMessageDialog(null, "You answered " + count +
                                          " out of " + questions.length +
                                          " questions correctly.");
            }
        }

  9. #9
    saytri is offline Member
    Join Date
    Dec 2007
    Posts
    34
    Rep Power
    0

    Default

    Yeah i understood well now. Thanks a lot for your help and time in helping me figure out these problems. I really appreciate your help a lot. You'r Awesome. Thanks again. :-) Best Wishes!

Similar Threads

  1. Help with code (static error)
    By oceansdepth in forum New To Java
    Replies: 1
    Last Post: 03-28-2008, 04:32 AM
  2. I need help fixing my code.. or non code?
    By MrHuggykins in forum New To Java
    Replies: 1
    Last Post: 03-19-2008, 10:12 PM
  3. error in code
    By dirtycash in forum New To Java
    Replies: 2
    Last Post: 12-06-2007, 11:40 PM
  4. error stack when I try to execute my code
    By paty in forum New To Java
    Replies: 1
    Last Post: 08-02-2007, 08:32 PM
  5. Replies: 1
    Last Post: 04-26-2007, 03:52 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •