Page 1 of 2 12 LastLast
Results 1 to 20 of 33
  1. #1
    mcal is offline Member
    Join Date
    Jan 2008
    Posts
    39
    Rep Power
    0

    Default For loop problem

    I'm really stuck. I am making a quiz, where questions are stored in a binary file. The answers are stored in an array. My problem comes when i have to compare the answer entered by the user to the correct answer. The correct answers are stored in an array. I tried to do a for loop, but its not working. (Infact everything inside the for loop isn't working) Can someone pls help me because i really got stuck and i can't continue programming with such a problem. Thanks a lot. :-)

    This is the code:
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.event.ActionListener.*;
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    import java.util.Calendar;
    import java.awt.image.*;
    import javax.imageio.*;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.DataOutputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    
    
     
    public class GQ extends JFrame implements ActionListener {
        private static final int FRAME_WIDTH = 1024;
        private static final int FRAME_HEIGHT = 768;
        private static final int FRAME_X_ORIGIN = 0;
        private static final int FRAME_Y_ORIGIN = 0;
        
      
        
        AnswerStore answerStore = new AnswerStore();
        boolean timeForMore;
        
       
                         
           public GQ() {
            
          
            Container contentPane;  
            contentPane = getContentPane();
    
            JButton button1, button2, button3, button4, button5;
            
            setSize (FRAME_WIDTH, FRAME_HEIGHT);
            setTitle("Geography Quiz");
            setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
            
                    
            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 static void main (String[] args) {
            
            JOptionPane.showMessageDialog(null, "This is a Geography Quiz");
            JOptionPane.showMessageDialog(null, "Good Luck");
     
            
                GQ frame = new GQ();
                frame.setVisible(true);
               
                new GQ();
                GQ File = new GQ();
                
          }
     
            String ac = event.getActionCommand();
            String[] question = null;
            String[] answers = null;
         
                
             if(ac.equals("b2")) {
                
    		     
                question = readFile("rivers.dat");
                answers = answerStore.riverAnswers;
            
          
            
            } else if (ac.equals("b4")) {
                System.exit(0);
               }
              
            
             askQuestions(question, answers); 
           
           
        }
        
       public void stopAndShowResults() {
            
            timeForMore = false;  // used for countdown. 
        }
           
        
     public String[] readFile(String path) {
            StringBuilder sb = new StringBuilder();
            String separator = "\n";
            String question;
         try{
    
          File aFile  = new File( "rivers.dat" );
          // create an output stream to the file
          FileInputStream aFileInStream = new FileInputStream ( aFile );
          // create a data output stream to the file output stream
          DataInputStream aDataInStream = new DataInputStream ( aFileInStream );
    
         
             question   = aDataInStream.readUTF();
             aFileInStream.close();
             JOptionPane.showInputDialog(null,question);
    
           
         
        }
              catch( FileNotFoundException e )
          {
             System.out.println( e.getMessage() );
             System.exit(1);
          }    
          
          catch(IOException e)
          {
             System.out.println( e.getMessage() );
             System.exit(1);
          }
               
            return sb.toString().split("\\n");
        }
     
    
        public void askQuestions(String[] question, String[] answers) {
          
            int count = 0;
            int point = 0;
            
            
           for(int j = 0; j < question.length; j++) { // anything inside in this for loop isn't working.
                
            timeForMore = true;
               String input = JOptionPane.showInputDialog(null,question[j]);// shows questions in a dialog box together with input line
                
                JOptionPane.showInputDialog(null,question);
                if(answers[j].equals(input))
                  { 
                    
                    count++;  // incrementing counter if entered answer is correct
                    point++;
                 }
                if(!timeForMore) // if time is over, the program executes the loop an stops asking questions.
                    break; 
         }
             
              
          
           
        JOptionPane.showMessageDialog(null, "You answered " + count +
                                          " out of " + question.length +
                                          " questions correctly.");
                int percent = (count*100)/question.length;
            JOptionPane.showMessageDialog(null, "Your Geography Quiz score is " + percent + " % ");
               
               
    class AnswerStore  {  // storing answers of each quiz in arrays
        String[] tectonicAnswers = {
            "Hellenic", "destructive", "100km", "Italy", "Wegner",
            "Mariana", "Sicily", "created", "constructive", "Mediterranean", "ggg",
            "ggg", "ggg"
        };
        
        String[] riverAnswers = {
            "Gorges", "Meanders", "Levees", "Yes", "Less Economic Developed Countries",
            "crescent shaped lakes", "More Economic Developed Countries", "No", "River Discharge", "No", "",
            "", ""
        };
        
        String[] rockAnswers = {
            "40km", "Igneous Rock", "Sedimentary", "Basalt", "Organic",
            "pressure", "Oolites", "Igneous", "dark black", "basalt", "",
            "", ""
        };
    
    
         }
    
    }

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

    Default

    Java Code:
        private void askQuestions(String[] questions, String[] answers) {
            int count = 0;
            int point = 0;
            for(int j = 0; j < questions.length; j++) {
                if(!timeForMore)
                    break;
                String input = JOptionPane.showInputDialog(null, questions[j]);
                if(answers[j].equals(input)) { 
                    count++;
                    point++;
                }   
            }
            JOptionPane.showMessageDialog(null, "You answered " + count +
                                          " out of " + questions.length +
                                          " questions correctly.");
            JOptionPane.showMessageDialog(null, "Your Geography Quiz score is " +
                                                     ((point*100)/10) + " % ");
            
            if(point>=0 && point<=3) {
                JOptionPane.showMessageDialog(null, "You need to Improve");
            }
      
            if(point>=4 && point<=7) {
                  JOptionPane.showMessageDialog(null, "Good");
            }
               
            if(point>=8 && point<=10) {
                  JOptionPane.showMessageDialog(null, "You did Great");
            }
        }

  3. #3
    mcal is offline Member
    Join Date
    Jan 2008
    Posts
    39
    Rep Power
    0

    Default

    Hey thanks a lot. But i think the problem is when it comes to compare the answers. I have a problem, because i was first using a textfile, and now my tutor told me that i should use a binary file to store the questions. And i really got confused of how am i going to arrange my program. Do write to a binary file do i have to write each question in the java source code? Because i think in this way there will be a lot of repetitive code. And if so how am i going to compare the answer with each correct answer? II'm really confused. Thanks for your help. You'r really a great person. :-) Thanks again.

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

    Default

    Did you see the example in Data Streams?

  5. #5
    mcal is offline Member
    Join Date
    Jan 2008
    Posts
    39
    Rep Power
    0

    Default

    Thanks. That helped a lot. I just got a problem. Because, i don't know why but the for loop isn't working. So the counter isn't being incremented and when time is over it still continues displaying the questions. It doesn't even check whether the answers are correct or not. Do i have something wrong in the for loop? Thanks a lot for your help. :-)

    This is the code:

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.event.ActionListener.*;
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    import java.util.Calendar;
    import java.awt.image.*;
    import javax.imageio.*;
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.IOException;
    import java.io.EOFException;
    
    
    
    
     
    public class GQ extends JFrame implements ActionListener {
        private static final int FRAME_WIDTH = 1024;
        private static final int FRAME_HEIGHT = 768;
        private static final int FRAME_X_ORIGIN = 0;
        private static final int FRAME_Y_ORIGIN = 0;
        
        private JLabel prompt;
        private JPanel image;
        private JLabel response;
        private JMenu  fileMenu;
        private JMenu  HelpMenu;
        private JMenu  OptionMenu;
       
        static final String dataFile1 = "plate_tectonics.dat";
        static final String dataFile2 = "rivers.dat";
        static final String dataFile3 = "rocks.dat";
        AnswerStore answerStore = new AnswerStore();
        boolean timeForMore;
        String question;
        
       public GQ() {
            
          
            Container contentPane;  
            contentPane = getContentPane();
    
            JButton button1, button2, button3, button4, button5;
            
            setSize (FRAME_WIDTH, FRAME_HEIGHT);
            setTitle("Geography Quiz");
            setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
            
            createFileMenu();
            createHelpMenu();
            createOptionMenu();
    
            
            JMenuBar menuBar= new JMenuBar();
            setJMenuBar(menuBar);
            menuBar.add(fileMenu);
            menuBar.add(HelpMenu);
            menuBar.add(OptionMenu);
        
            response=new JLabel();
            response.setBounds(50, 50, 250, 50);
            contentPane.add(response);
            
            response=new JLabel();
            response.setBounds(50, 50, 250, 50);
            contentPane.add(response);
            
            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 static void main (String[] args) {
            
            JOptionPane.showMessageDialog(null, "This is a Geography Quiz");
            JOptionPane.showMessageDialog(null, "Good Luck");
     
            
                GQ frame = new GQ();
                frame.setVisible(true);
               
                new GQ();
                GQ File = new GQ();
                
          }
     
         
          
          
            
            String ac = event.getActionCommand();
            String[] questions = null;
            String[] answers = null;
            if (ac.equals("b1")) {
                 final JPF1 appRef = new JPF1(); 
                 JFrame frame = new JFrame("CountDown");
    		     MP panel = new MP();
    		     panel.addCountDownListener(appRef); 
                 panel.setVisible(true);
    		     frame.setSize(panel.getSize());
    		     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		     frame.setContentPane(panel);
    		     frame.setVisible(true);
    		     
    		    questions = readFile1("plate_tectonics.dat");
                answers = answerStore.tectonicAnswers;
                
                askQuestions(questions, answers);  // here its isn't reading the file
    	
            } else if(ac.equals("b2")) {
                 final JPF1 appRef = new JPF1();
                 JFrame frame = new JFrame("CountDown");
    		     MP panel = new MP();
    		     panel.addCountDownListener(appRef); 
                 panel.setVisible(true);
    		     frame.setSize(panel.getSize());
    		     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		     frame.setContentPane(panel);
    		     frame.setVisible(true);
    		     
                questions = readFile2("rivers.dat");
                answers = answerStore.riverAnswers;
                
                askQuestions(questions, answers); 
            
            } else if(ac.equals("b3")) {
                 final JPF1 appRef = new JPF1();
                 JFrame frame = new JFrame("CountDown");
    		     MP panel = new MP();
    		     panel.addCountDownListener(appRef); 
                 panel.setVisible(true);
    		     frame.setSize(panel.getSize());
    		     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		     frame.setContentPane(panel);
    		     frame.setVisible(true);
                 
    		     questions = readFile3("rocks.dat");
                answers = answerStore.rockAnswers;
                
                askQuestions(questions, answers); 
            
            } else if (ac.equals("b4")) {
                System.exit(0);
               }
              
         }
        
         public void stopAndShowResults() {
            
            timeForMore = false;  // used for countdown. 
        }
           
        private String[] readFile1(String path) {
            StringBuilder sb = new StringBuilder();
            String separator = "\n";
            String question;
            
         DataInputStream in = null;
           
            try {
                in = new DataInputStream(new
                        BufferedInputStream(new FileInputStream(dataFile1)));
    
               
                String desc;
    
                  try {
                    while (true) {
                      
                        desc = in.readUTF();
                         JOptionPane.showInputDialog(null, desc);
                      
                    }
                } catch (EOFException e) { }
                
            }
           catch(IOException e)
          {
             System.out.println( e.getMessage() );
             System.exit(1);
          }
            
              return sb.toString().split("\\n");
        }
              
      private String[] readFile2(String path) {
            StringBuilder sb = new StringBuilder();
            String separator = "\n";
            String question;
            
         DataInputStream in = null;
           
            try {
                in = new DataInputStream(new
                        BufferedInputStream(new FileInputStream(dataFile2)));
    
               
                String desc;
    
                  try {
                    while (true) {
                      
                        desc = in.readUTF();
                         JOptionPane.showInputDialog(null, desc);
                      
                    }
                } catch (EOFException e) { }
                
            }
           catch(IOException e)
          {
             System.out.println( e.getMessage() );
             System.exit(1);
          }
            
              return sb.toString().split("\\n");
        }
               
        private String[] readFile3(String path) {
            StringBuilder sb = new StringBuilder();
            String separator = "\n";
            String question;
            
         DataInputStream in = null;
           
            try {
                in = new DataInputStream(new
                        BufferedInputStream(new FileInputStream(dataFile3)));
    
               
                String desc;
    
                  try {
                    while (true) {
                      
                        desc = in.readUTF();
                         JOptionPane.showInputDialog(null, desc);
                      
                    }
                } catch (EOFException e) { }
                
            }
           catch(IOException e)
          {
             System.out.println( e.getMessage() );
             System.exit(1);
          }
            
              return sb.toString().split("\\n");
        }
               
        
      public void askQuestions(String[] questions, String[] answers) {
          
            int count = 0;
            int point = 0;
            
            
           for(int j = 0; j < questions.length; j++) {
                
               timeForMore = true;
               
              
              Random generator = new Random();
              int randomIndex = generator.nextInt(questions.length); 
              String input = JOptionPane.showInputDialog(null, questions[randomIndex]); 
    
            
              if(answers[randomIndex].equalsIgnoreCase(input))
               
               count++;  // incrementing counter if entered answer is correct
               point++;
              
              
         if(!timeForMore) // if time is over, the program executes the loop an stops asking questions.
                    break; 
         }
             
                
          
                
                 
                JOptionPane.showMessageDialog(null, "You answered " + count +
                                          " out of " + questions.length +
                                          " questions correctly.");
                int percent = (count*100)/questions.length;
            JOptionPane.showMessageDialog(null, "Your Geography Quiz score is " + percent + " &#37; ");
               
                 
          }
          
          
     
       
          
    class AnswerStore  {  // storing answers of each quiz in arrays
        String[] tectonicAnswers = {
            "Hellenic", "destructive", "100km", "Italy", "Wegner",
            "Mariana", "Sicily", "created", "constructive", "Mediterranean", "ggg",
            "ggg", "ggg"
        };
        
        String[] riverAnswers = {
            "Gorges", "Meanders", "Levees", "Yes", "Less Economic Developed Countries",
            "crescent shaped lakes", "More Economic Developed Countries", "No", "River Discharge", "No", "",
            "", ""
        };
        
        String[] rockAnswers = {
            "40km", "Igneous Rock", "Sedimentary", "Basalt", "Organic",
            "pressure", "Oolites", "Igneous", "dark black", "basalt", "",
            "", ""
        };
    
    
         }
    
    }

    And this is the code to write to a binary file. (This is only one of the files):

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.event.ActionListener.*;
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    import java.util.Calendar;
    import java.awt.image.*;
    import javax.imageio.*;
    
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.Scanner;
    
    public class PlateTectonics {
        static final String dataFile = "plate_tectonics.dat";
    
        
       
        static final String[] plate_tectonics = { "When the continents were joined together they were called  a) Hellenic b) Pangaea c) Mariana",
                " When continents move towards each other they are called   a) Constructive b) Destructive c) Conservative",
                "At what depth does a subducted plate melt? a) 100km b) 300km c) 20km",
                "The Alps are found in a) Spain b) France c) Italy",
                "Who proposed the idea of Continental Drift a) Scientist Burges b) Scientist Wegner c) Scientist John",
               "Which is the deepest trench in the world? a) Hellenic b) Mariana c) Aegean",
                "The Volcanoe Etna is found in: a) Sicily b) Malta c) Cyprus",
                "At constructive plate margins crust is: a) Created b) Destroyed c) Conserved", 
                "When the continents move away from each other they are called: a) Passive Margins b) Constructive Margins c) Destructive Margins",
                " Hellenic trench is found in: a) Indian Ocean b) Mediterranean c) Atlantic Ocean" };
    
        public static void main(String[] args) throws IOException {
    
     
            DataOutputStream out = null;
            
            try {
                out = new DataOutputStream(new
                        BufferedOutputStream(new FileOutputStream(dataFile)));
    
                for (int i = 0; i < plate_tectonics.length; i ++) {
                   
                    out.writeUTF(plate_tectonics[i]);
                }
            } finally {
                out.close();
            }
    
            DataInputStream in = null;
        }   
           
    }
    Thanks again. :-)
    Last edited by mcal; 01-20-2008 at 07:04 PM.

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

    Default

    the for loop isn't working
    Let's have a look at the askQuestions method.
    Java Code:
    public void askQuestions(String[] questions, String[] answers) {
        // To begin with, are you certain that the questions array
        // and the answers array are the same length and have non-null
        // elements? If so, okay. If not, this is a good place to check.
        // See comment below this method for more about this.
        int count = 0;
        int point = 0;
    
    
        for(int j = 0; j < questions.length; j++) {
            // The "timeForMore" is a member variable (declared in
            // class scope) and is used as a flag, set in the
            // [i]stopAndShowResults[/i] method by another class.
            // If you set it to [i]true[/i] for each trip thru this
            // loop you may interfere with its function which is to
            // wait until the timing class notifies this class that
            // the time is up and we should break out of the
            // 'askingQuestions' loop. This should be reset when you
            // start timing each question_and_answer session; perhaps
            // when you enter this method but possibley not. So this
            // next line should be removed from here.
            timeForMore = true;
    
            // You will get better results with a Random instance if
            // you declare it as a member variable (in class scope)
            // rather than making a new one for each trip thru this
            // loop. So move this next line to the member variable
            // declarations area up above the constructor.
            Random generator = new Random();
            // Question for later - how will you prevent "generator"
            // from returning duplicate indices? 
            int randomIndex = generator.nextInt(questions.length); 
            String input = JOptionPane.showInputDialog(null, questions[randomIndex]); 
    
            [i]the counter isn't being incremented[/i]
            // There are no curley braces after this [i]if[/i]
            // statement to form a code block so the next statement,
            // viz, "count++;", is the only statement affected/protected
            // by this [i]if[/i] statement. If you add a curley brace
            // after the [i]if[/i] statement and after the "point++"
            // statement then boith statements will be
            // included_in/controlled_protected_by the [i]if[/i] statement.
            if(answers[randomIndex].equalsIgnoreCase(input))
    
                count++;  // incrementing counter if entered answer is correct
                point++;
    
    
            // if time is over, the program executes the loop an stops
            // asking questions.
            if(!timeForMore)
                break;
        }
    
             
                
          
                
                 
        JOptionPane.showMessageDialog(null, "You answered " + count +
                                            " out of " + questions.length +
                                            " questions correctly.");
        int percent = (count*100)/questions.length;
        JOptionPane.showMessageDialog(null, "Your Geography Quiz score is " +
                                      percent + " % ");
               
                 
    }
    I asked about the "questions" array argument to the askQuestions method because of this:
    Java Code:
    try {
        while (true) {
            // Here you are saving the read input in the "desc" variable but
            // you do not add it ("desc") to the StringBuilder. So when the
            // StringBuilder is returned as a string it will be empty.
            desc = in.readUTF();
    
    
        }
    } catch (EOFException e) { }
    when time is over it still continues displaying the questions
    Could be many things. First remove the reassignment of "timeForMore" from the for loop, mentioned above. Then, as a place to start, since we are working in/on the askQuestions method, try printing out the value of "timeForMore" in the "askQuestions" for loop to see if the timing class changes this flags value when the time has expired.

    It doesn't even check whether the answers are correct or not.
    This could be because of a zero–length array being passed to the askQuestions method as the "questions" argument.
    Note: I see you have made an edit since I started writing this.

  7. #7
    mcal is offline Member
    Join Date
    Jan 2008
    Posts
    39
    Rep Power
    0

    Default

    Oh that was so helpful. I really am thankful. But i can't understand why the counter still isn't incremented. It seems when i call this:

    Java Code:
     askQuestions(questions, answers);
    it just skips the for loop and continues displaying the others:

    Java Code:
    JOptionPane.showMessageDialog(null, "You answered " + count +
                                          " out of " + questions.length +
                                          " questions correctly.");
                int percent = (count*100)/questions.length;
            JOptionPane.showMessageDialog(null, "Your Geography Quiz score is " + percent + " &#37; ");
    It is just showing: "You answered 0 out of 1 questions correctly". How come it is saying one question when i have 10 questions? I really got confused. Thanks a lot for your help. You are really kind, and i really appreciate your help. When i was working with the textfile, the program worked fine, but now (with the binary file) it isn't.

    This is the whole code, where i arranged what you told me:

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.event.ActionListener.*;
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    import java.util.Calendar;
    import java.awt.image.*;
    import javax.imageio.*;
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.IOException;
    import java.io.EOFException;
    
    public class GQ extends JFrame implements ActionListener {
        private static final int FRAME_WIDTH = 1024;
        private static final int FRAME_HEIGHT = 768;
        private static final int FRAME_X_ORIGIN = 0;
        private static final int FRAME_Y_ORIGIN = 0;
        
        private JLabel prompt;
        private JPanel image;
        private JLabel response;
        private JMenu  fileMenu;
        private JMenu  HelpMenu;
        private JMenu  OptionMenu;
       
        static final String dataFile1 = "plate_tectonics.dat";
        static final String dataFile2 = "rivers.dat";
        static final String dataFile3 = "rocks.dat";
        AnswerStore answerStore = new AnswerStore();
        boolean timeForMore;
        
        
      
      
    	
      public GQ() {
            
          
            Container contentPane;  
            contentPane = getContentPane();
    
            JButton button1, button2, button3, button4, button5;
            
            setSize (FRAME_WIDTH, FRAME_HEIGHT);
            setTitle("Geography Quiz");
            setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
            
            createFileMenu();
            createHelpMenu();
            createOptionMenu();
    
            
            JMenuBar menuBar= new JMenuBar();
            setJMenuBar(menuBar);
            menuBar.add(fileMenu);
            menuBar.add(HelpMenu);
            menuBar.add(OptionMenu);
        
            response=new JLabel();
            response.setBounds(50, 50, 250, 50);
            contentPane.add(response);
            
            response=new JLabel();
            response.setBounds(50, 50, 250, 50);
            contentPane.add(response);
            
            button1 = new JButton("Plate Tectonics");
            button2 = new JButton("Rivers");
            button3 = new JButton("Rocks");
            button4 = new JButton("Quit");
            
            button1.setBounds(350,225,300,50);
            button2.setBounds(350,325,300,50);
            button3.setBounds(350,425,300,50);
            button4.setBounds(350,525,300,50);
            
            button1.setFont(new Font("Arial", Font.BOLD, 30));
            button2.setFont(new Font("Arial", Font.BOLD, 30));
            button3.setFont(new Font("Arial", Font.BOLD, 30));
            button4.setFont(new Font("Arial", Font.BOLD, 30));
            
            button1.setBorder(BorderFactory.createRaisedBevelBorder());
            button2.setBorder(BorderFactory.createRaisedBevelBorder());
            button3.setBorder(BorderFactory.createRaisedBevelBorder());
            button4.setBorder(BorderFactory.createRaisedBevelBorder());
            
            
            button1.setBackground (Color.pink);
            button1.setForeground (Color.blue);
            button2.setBackground (Color.pink);
            button2.setForeground (Color.blue);
            button3.setBackground (Color.pink);
            button3.setForeground (Color.blue);
            button4.setBackground (Color.pink);
            button4.setForeground (Color.blue);
         
            
            prompt = new JLabel( );
    
            prompt.setText("Geography Quiz");
            prompt.setSize(900,50);
            prompt.setLocation(350,30);
            prompt.setFont(new Font("Times New Roman", Font.BOLD, 40));
            prompt.setForeground(Color.red);
            contentPane.add(prompt);
            
            prompt = new JLabel( );
    
            prompt.setText("Choose any of the following:");
    
            prompt.setSize(900,80);
    
            prompt.setLocation(325,100);
            
            prompt.setFont(new Font("Times New Roman", Font.BOLD, 30));
            
            contentPane.add(prompt);
    
     
            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);
            
            setDefaultCloseOperation(EXIT_ON_CLOSE);
    
            contentPane.setBackground(Color.green);
            contentPane.setLayout(new BorderLayout());
            Test4Rx imagePanel = new Test4Rx("geo2.jpg");
            contentPane.add(imagePanel, "North");
            contentPane.add(new Test4Rx("geo2.jpg"));
            pack();
            setLocationRelativeTo(null);
            setVisible(true);
    		
        }
      
        public static void main (String[] args) {
            
            JOptionPane.showMessageDialog(null, "This is a Geography Quiz");
            JOptionPane.showMessageDialog(null, "Good Luck");
     
            
                GQ frame = new GQ();
                frame.setVisible(true);
               
                new GQ();
                GQ File = new GQ();
                
          }
     
            public void actionPerformed(ActionEvent event) {
            String menuName;
            JFileChooser chooser;
          
            int status;
            
            chooser=new JFileChooser();
    
            menuName = event.getActionCommand();
    
            //Action performed by 'Quit' menu item.
            if(menuName.equals("Quit")){
                System.exit(0);
            }
           
            
            if(menuName.equals("About Quiz")){
                JOptionPane.showMessageDialog(null, " This is a Geography Quiz. " +
                                                    " You can choose from 3 different quizzes. " +
                                                    " Questions should be answered within 50 seconds. ");
            
                                                   
                                                }    
        
        if(menuName.equals("Add a Plate Tectonic Question")){
               
                 
            final JPF2 appRef = new JPF2();
            final JFrame frame = new JFrame("Password");
    
            JLabel jlbPassword = new JLabel("Enter the password: ");
            JPasswordField jpwName = new JPasswordField(10);
            jpwName.setEchoChar('*');
            jpwName.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JPasswordField input = (JPasswordField)e.getSource();
                    char[] password = input.getPassword();
                    if (isPasswordCorrect(password)) {
                        JOptionPane.showMessageDialog(frame, "Correct  password.");
                       
                       try {
                
                         String question = JOptionPane.showInputDialog(null, "Enter new question");
         
         
    
                   File aFile  = new File( "plate_tectonics.dat" );
          // create an output stream to the file
                   FileOutputStream aFileOutStream = new FileOutputStream ( aFile );
          // create a data output stream to the file output stream
                   DataOutputStream aDataOutStream = new DataOutputStream ( aFileOutStream );
    
          // write data to file
                  aDataOutStream.writeUTF( question );
         
                  aFileOutStream.close();
    
                            
                            
                        
                        }catch(IOException event){
                       System.out.println("There was a problem:" + e);
    
                                   }
                          
              } else {
                        JOptionPane.showMessageDialog(frame, "Sorry. Try again.",
                            "Error Message", JOptionPane.ERROR_MESSAGE);
                    }
                }
            });
    
            JPanel jplContentPane = new JPanel(new BorderLayout());
            jplContentPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
            jplContentPane.add(jlbPassword, BorderLayout.WEST);
            jplContentPane.add(jpwName, BorderLayout.CENTER);
    
            frame.setContentPane(jplContentPane);
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) { System.exit(0); }
            });
            frame.pack();
            frame.setVisible(true);
     
                                                   
        }    
        
         if(menuName.equals("Add a River Question")){
               
                 
            final JPF2 appRef = new JPF2();
            final JFrame frame = new JFrame("Password");
    
            JLabel jlbPassword = new JLabel("Enter the password: ");
            JPasswordField jpwName = new JPasswordField(10);
            jpwName.setEchoChar('*');
            jpwName.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JPasswordField input = (JPasswordField)e.getSource();
                    char[] password = input.getPassword();
                    if (isPasswordCorrect(password)) {
                        JOptionPane.showMessageDialog(frame, "Correct  password.");
                       
                       
                
                        try {
                
                         String question = JOptionPane.showInputDialog(null, "Enter new question");
         
         
    
                   File aFile  = new File( "rivers.dat" );
          // create an output stream to the file
                   FileOutputStream aFileOutStream = new FileOutputStream ( aFile );
          // create a data output stream to the file output stream
                   DataOutputStream aDataOutStream = new DataOutputStream ( aFileOutStream );
    
          // write data to file
                  aDataOutStream.writeUTF( question );
         
                  aFileOutStream.close();
    
                            
                            
                        
                        }catch(IOException event){
                       System.out.println("There was a problem:" + e);
    
                                   }
                        
                          
              } else {
                        JOptionPane.showMessageDialog(frame, "Sorry. Try again.",
                            "Error Message", JOptionPane.ERROR_MESSAGE);
                    }
                }
            });
    
            JPanel jplContentPane = new JPanel(new BorderLayout());
            jplContentPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
            jplContentPane.add(jlbPassword, BorderLayout.WEST);
            jplContentPane.add(jpwName, BorderLayout.CENTER);
    
            frame.setContentPane(jplContentPane);
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) { System.exit(0); }
            });
            frame.pack();
            frame.setVisible(true);
     
                                                   
        }   
        
         if(menuName.equals("Add a Rocks Question")){
               
                 
            final JPF2 appRef = new JPF2();
            final JFrame frame = new JFrame("Password");
    
            JLabel jlbPassword = new JLabel("Enter the password: ");
            JPasswordField jpwName = new JPasswordField(10);
            jpwName.setEchoChar('*');
            jpwName.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JPasswordField input = (JPasswordField)e.getSource();
                    char[] password = input.getPassword();
                    if (isPasswordCorrect(password)) {
                        JOptionPane.showMessageDialog(frame, "Correct  password.");
                       
                        try {
                
                         String question = JOptionPane.showInputDialog(null, "Enter new question");
         
         
    
                    File aFile  = new File( "rocks.dat" );
          // create an output stream to the file
                   FileOutputStream aFileOutStream = new FileOutputStream ( aFile );
          // create a data output stream to the file output stream
                   DataOutputStream aDataOutStream = new DataOutputStream ( aFileOutStream );
    
          // write data to file
                  aDataOutStream.writeUTF( question );
         
                  aFileOutStream.close();
    
                            
                            
                        
                        }catch(IOException event){
                       System.out.println("There was a problem:" + e);
    
                                   }
                        
                          
              } else {
                        JOptionPane.showMessageDialog(frame, "Sorry. Try again.",
                            "Error Message", JOptionPane.ERROR_MESSAGE);
                    }
                }
            });
    
            JPanel jplContentPane = new JPanel(new BorderLayout());
            jplContentPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
            jplContentPane.add(jlbPassword, BorderLayout.WEST);
            jplContentPane.add(jpwName, BorderLayout.CENTER);
    
            frame.setContentPane(jplContentPane);
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) { System.exit(0); }
            });
            frame.pack();
            frame.setVisible(true);
     
                                                   
        }   
            
            String ac = event.getActionCommand();
            String[] questions = null;
            String[] answers = null;
            if (ac.equals("b1")) {
                 final JPF1 appRef = new JPF1(); 
                 JFrame frame = new JFrame("CountDown");
    		     MP panel = new MP();
    		     panel.addCountDownListener(appRef); 
                 panel.setVisible(true);
    		     frame.setSize(panel.getSize());
    		     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		     frame.setContentPane(panel);
    		     frame.setVisible(true);
    		     
    		    questions = readFile1("plate_tectonics.dat");
                answers = answerStore.tectonicAnswers;
                
                 askQuestions(questions, answers); 
    	
            } else if(ac.equals("b2")) {
                 final JPF1 appRef = new JPF1();
                 JFrame frame = new JFrame("CountDown");
    		     MP panel = new MP();
    		     panel.addCountDownListener(appRef); 
                 panel.setVisible(true);
    		     frame.setSize(panel.getSize());
    		     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		     frame.setContentPane(panel);
    		     frame.setVisible(true);
    		     
                questions = readFile2("rivers.dat");
                answers = answerStore.riverAnswers;
                
                askQuestions(questions, answers); 
            
            } else if(ac.equals("b3")) {
                 final JPF1 appRef = new JPF1();
                 JFrame frame = new JFrame("CountDown");
    		     MP panel = new MP();
    		     panel.addCountDownListener(appRef); 
                 panel.setVisible(true);
    		     frame.setSize(panel.getSize());
    		     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		     frame.setContentPane(panel);
    		     frame.setVisible(true);
                 
    		     questions = readFile3("rocks.dat");
                answers = answerStore.rockAnswers;
                
                askQuestions(questions, answers); 
            
            } else if (ac.equals("b4")) {
                System.exit(0);
               }
              
            
             // calls the questions from textfile
           
           
        }
        
        private void createFileMenu(){ // creating a File Menu
            JMenuItem item;
    
            fileMenu = new JMenu("File");
    
            item = new JMenuItem("Quit");        //Quit
            item.addActionListener(this);
            fileMenu.add(item);
        }
    
        //Create Edit Menu
        private void createHelpMenu(){
            JMenuItem item;
            HelpMenu=new JMenu("Help");
    
            item = new JMenuItem("About Quiz");         
            item.addActionListener(this);
            HelpMenu.add(item);
    
            item = new JMenuItem("Help about Quiz");       
            item.addActionListener(this);
            HelpMenu.add(item);
            
          
    
            
        }
        
         private void createOptionMenu(){
            JMenuItem item;
            OptionMenu=new JMenu("Option");
    
            item = new JMenuItem("Add a Plate Tectonic Question");         
            item.addActionListener(this);
            OptionMenu.add(item);
            
            item = new JMenuItem("Add a River Question");         
            item.addActionListener(this);
            OptionMenu.add(item);
            
            item = new JMenuItem("Add a Rocks Question");         
            item.addActionListener(this);
            OptionMenu.add(item);
    
            
    
            
        }
    
       
    
       
    
    
        public void stopAndShowResults() {
            
            timeForMore = false;  // used for countdown. 
        }
           
        
    
        
     
        private String[] readFile1(String path) {
            StringBuilder sb = new StringBuilder();
            String separator = "\n";
            String question;
            
         DataInputStream in = null;
           
            try {
                in = new DataInputStream(new
                        BufferedInputStream(new FileInputStream(dataFile1)));
    
               
                String desc;
    
                  try {
                    while (true) {
                      
                        desc = in.readUTF();
                        JOptionPane.showInputDialog(null, desc);
                      
                    }
                } catch (EOFException e) { }
                
            }
           catch(IOException e)
          {
             System.out.println( e.getMessage() );
             System.exit(1);
          }
            
              return sb.toString().split("\\n");
        }
              
      private String[] readFile2(String path) {
            StringBuilder sb = new StringBuilder();
            String separator = "\n";
            String question;
            
         DataInputStream in = null;
           
            try {
                in = new DataInputStream(new
                        BufferedInputStream(new FileInputStream(dataFile2)));
    
               
                String desc;
    
                  try {
                    while (true) {
                      
                        desc = in.readUTF();
                         JOptionPane.showInputDialog(null, desc);
                      
                    }
                } catch (EOFException e) { }
                
            }
           catch(IOException e)
          {
             System.out.println( e.getMessage() );
             System.exit(1);
          }
            
              return sb.toString().split("\\n");
        }
               
        private String[] readFile3(String path) {
            
            String question;
            
         DataInputStream in = null;
           
            try {
                in = new DataInputStream(new
                        BufferedInputStream(new FileInputStream(dataFile3)));
    
               
                String desc;
    
                  try {
                    while (true) {
                      
                        desc = in.readUTF();
                        JOptionPane.showInputDialog(null, desc); 
                      
                    }
                } catch (EOFException e) { }
                
            }
           catch(IOException e)
          {
             System.out.println( e.getMessage() );
             System.exit(1);
          }
            
    
        }
               
        
      public void askQuestions(String[] questions, String[] answers) {
          
            int count = 0;
            int point = 0;
            Random generator = new Random();
            
           for(int j = 0; j < questions.length; j++) {
              
               
              
              
              int randomIndex = generator.nextInt(questions.length); 
              String input = JOptionPane.showInputDialog(null, questions[randomIndex]); 
    
            
              if(answers[randomIndex].equalsIgnoreCase(input))
               {
               count++;  // incrementing counter if entered answer is correct
               point++;
               }
              
              if(!timeForMore) // if time is over, the program executes the loop an stops asking questions.
                    break; 
         }
             
                
          
                
                 
                JOptionPane.showMessageDialog(null, "You answered " + count +
                                          " out of " + questions.length +
                                          " questions correctly.");
                int percent = (count*100)/questions.length;
            JOptionPane.showMessageDialog(null, "Your Geography Quiz score is " + percent + " % ");
               
                 try {
                  BufferedWriter out;
                  String name = JOptionPane.showInputDialog(null, "Enter your name");
                  String type = JOptionPane.showInputDialog(null, "Enter your quiz type");
                  out = new BufferedWriter(new FileWriter("players.txt",true));
    
    
    
                 out.write(name); //Writing to the textfile (the name entered by user)
                
                 out.write(getSpace(20- name.length())); // Here 20 is max length possible change accordingly
                 String trimmedStr = name.trim();
                 out.write(String.valueOf(percent+ " % "));
                 out.write("         ");
                 out.write(type);
                 out.newLine(); //write a new line to the textfile so the next time it writes to the file it does it on the next line
                 out.close();
              }catch(IOException e){
                 System.out.println("There was a problem:" + e);
    
                                   }
        
               
               if(point>=0 && point<=3)
              {
                 
                  JOptionPane.showMessageDialog(null, "You need to Improve");
               }
               
               
             if(point>=4 && point<=7)
              {
                 
                  JOptionPane.showMessageDialog(null, "Good");
               }
               
               if(point>=8 && point<=10)
              {
                 
                  JOptionPane.showMessageDialog(null, "You did Great");
               }
               
               ReadDataFileToPanel scorelist = new ReadDataFileToPanel(); // calling class to view the score list
             
              
          }
          
          
     
       
          
          public static String getSpace(int length){
    		String str = "";
    		for(int i = 0 ; i < length ; i++	){
    			str = str + " " ;
    			 
        
    		}
    		return str ;
    	}
    	
    	  private static boolean isPasswordCorrect(char[] inputPassword) {
            char[] actualPassword = { 'h', 'e', 'l', 'l' };
            if (inputPassword.length != actualPassword.length)
                return false;		//Return false if lengths are unequal
            for (int i = 0;  i < inputPassword.length; i ++)
                if (inputPassword[i] != actualPassword[i])
                    return false;
            return true;
        }
       
    
    
    class AnswerStore  {  // storing answers of each quiz in arrays
        String[] tectonicAnswers = {
            "Hellenic", "destructive", "100km", "Italy", "Wegner",
            "Mariana", "Sicily", "created", "constructive", "Mediterranean" 
        };
        
        String[] riverAnswers = {
            "Gorges", "Meanders", "Levees", "Yes", "Less Economic Developed Countries",
            "crescent shaped lakes", "More Economic Developed Countries", "No", "River Discharge", "No"
        };
        
        String[] rockAnswers = {
            "40km", "Igneous Rock", "Sedimentary", "Basalt", "Organic",
            "pressure", "Oolites", "Igneous", "dark black", "basalt"
        };
    
    
         }
    
    }

    Thnaks again. :-)
    Last edited by mcal; 01-20-2008 at 08:21 PM.

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

    Default

    it just skips the for loop ... How come it is saying one question when i have 10 questions?

    Back to the while loop in the three readFileXXX methods in which you do not save the data you are reading from the file into the StringBuilder.
    Java Code:
    try {
        while (true) {
            // Here you are saving the read input in the "desc" variable but
            // you do not add it ("desc") to the StringBuilder. So when the
            // StringBuilder is returned as a string it will be empty.
            desc = in.readUTF();
    
            // Need to add the newly-read data to the StringBuilder:
            sb.append(desc + separator);
    
        }
    } catch (EOFException e) { }
    To test/explore this idea/suggestion try adding a print statement at the beginning of the askQusestions method to check the incoming arguments, like this:
    Java Code:
        private void askQuestions(String[] questions, String[] answers) {
            System.out.printf("questions = %s%nanswers = %s%n", // debugging
                               Arrays.toString(questions),
                               Arrays.toString(answers));

  9. #9
    mcal is offline Member
    Join Date
    Jan 2008
    Posts
    39
    Rep Power
    0

    Default

    Ok thanks a lot. Just one last problem. When i removed the string builder, now it is issuing a missing return statement. What is missing? And it is always displying the questions 2 times. First it displays the questions, and then for a second time it display them again. Thanks a lot. And i really have to thank you for your help. Thanks again. :-)

    In this code:

    Java Code:
    private String[] readFile3(String path) {
            StringBuilder sb = new StringBuilder();
            String separator = "\n";
           
            
         DataInputStream in = null;
           
            try {
                in = new DataInputStream(new
                        BufferedInputStream(new FileInputStream(dataFile3)));
    
               
                String desc;
    
                  try {
                    while (true) {
                      
                        desc = in.readUTF();
                        JOptionPane.showInputDialog(null, desc); 
                      sb.append(desc + separator);
                    }
                } catch (EOFException e) { }
                
            }
           catch(IOException e)
          {
             System.out.println( e.getMessage() );
             System.exit(1);
          }
             
         
            // here i think is a missing return statement
        }
    Last edited by mcal; 01-20-2008 at 09:51 PM.

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

    Default

    Don't remove the StringBuilder. That is what is holding and sending (returning) the information (that the method reads from the file) back to the caller. The caller (the ActionListeners actionPerformed method) needs this information to send to the askQuestions method.
    Also, since the readFileXXX method(s) declare a return type of type "String" (vis–a–vis "null", ie, nothing to return to the caller) the method must return a value of type "String". The compiler is keeping us out of trouble.

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

    Default

    is always displying the questions 2 times
    Maybe the askQuestions method is being called more than once or there may be some logic glitch in the method or maybe two sets of questions were sent into the method in the "questions" array.

  12. #12
    mcal is offline Member
    Join Date
    Jan 2008
    Posts
    39
    Rep Power
    0

    Default

    Yeah you were right. Thanks for everything. You were really helpful! I really appreciated your help. :-) I'm very obliged. Thanks again. :-)
    Last edited by mcal; 01-20-2008 at 11:10 PM.

  13. #13
    mcal is offline Member
    Join Date
    Jan 2008
    Posts
    39
    Rep Power
    0

    Default

    Hi, i'm really sorry but i got stuck with an other problem. As you have told me previously, the method of random i have used isn't so efficient since it is displayin some of the question repetively. Is there another way, how i could generate the questions randomly without displaying some of the questions over again? Thanks a lot. I'm really obliged.

    Java Code:
    public void askQuestions(String[] questions, String[] answers) {
          
            int count = 0;
            int point = 0;
            
            
           for(int j = 0; j < questions.length; j++) {
                
          
               
              
              Random generator = new Random();
              int randomIndex = generator.nextInt(questions.length); 
              String input = JOptionPane.showInputDialog(null, questions[randomIndex]); 
    
            
              if(answers[randomIndex].equalsIgnoreCase(input))
               
               count++;  // incrementing counter if entered answer is correct
               point++;
              
              
          
           
           
           
           
    if(!timeForMore) 
                    break; 
         }
    Last edited by mcal; 01-21-2008 at 07:06 PM.

  14. #14
    tim's Avatar
    tim
    tim is offline Senior Member
    Join Date
    Dec 2007
    Posts
    435
    Rep Power
    7

    Default Old thread

    Hello mcal

    You have previously created a thread on this quiz problem. I have given you a solution for the repetitions. Please consider it. If you have problems with polymorphism or some of my methods, please inform us so that we can help you.

    Good luck. ;)
    Eyes dwelling into the past are blind to what lies in the future. Step carefully.

  15. #15
    mcal is offline Member
    Join Date
    Jan 2008
    Posts
    39
    Rep Power
    0

    Default

    Yeah i know, and i thank you for that. But to tell you the truth i didn't understand it, because i'm still a beginner, and i have never worked with vectors before. I really thank you, for helping me with that, but i wish that i would find something more simpler. Thanks Tim, i appreciate it a lot. Infact i posted again, because i'm trying to find a simpler method.

  16. #16
    tim's Avatar
    tim
    tim is offline Senior Member
    Join Date
    Dec 2007
    Posts
    435
    Rep Power
    7

    Default No problem

    Okay, I understand. :p

    Do you understand how to define and use classes? With that you can really simplify this problem.
    Eyes dwelling into the past are blind to what lies in the future. Step carefully.

  17. #17
    mcal is offline Member
    Join Date
    Jan 2008
    Posts
    39
    Rep Power
    0

    Default

    Yes i understand that. :-) How can i simplify this problem with that ? Thanks again.

  18. #18
    tim's Avatar
    tim
    tim is offline Senior Member
    Join Date
    Dec 2007
    Posts
    435
    Rep Power
    7

    Default

    We can use this class to handle quiz problems:
    Java Code:
    public class QuizProblem{
        private String question;
        private String answer;
        public boolean checkInput(String userAnswer){
            return answer.equals(userAnswer);
        }
        public String getAnswer(){
            return answer;
        }
        public String getQuestion(){
            return question;
        }
        public void setAnswer(String answer){
            this.answer = answer;
        }
        public void setQuestion(String question){
            this.question= question;
        }
        public QuizProblem(String question, String answer){
            this.question = question;
            this.answer = answer;
        }
    }
    Now, we can create an array of QuizProblem objects from a method. But, since you want to use arrays, we must know how many questions there are. I will assume that for every question you have an answer in an array. You have already loaded the questions in an array so now we have all we need.
    Look at this method:
    Java Code:
    public QuizProblem[] createQuizProblems(String[] questions; String[] answers){
        int length = questions.length;
        QuizProblem[] result = new QuizProblem[length];
        for (int i = 0; i < length; i++){
            QuizProblem current = new QuizProblem(questions[i], answers[i]);
            result[i] = current;
        }
        return result;
    }
    In your main method you can have:
    Java Code:
    question = readFile("rivers.dat");
    answers = answerStore.riverAnswers;
    QuizProblem[] quiz = createQuizProblems(question, answers);
    This may look trivial, but it gives us means of grouping the questions and answers together and it will make the asking of the questions later easier.

    Do you follow mcal?
    Eyes dwelling into the past are blind to what lies in the future. Step carefully.

  19. #19
    mcal is offline Member
    Join Date
    Jan 2008
    Posts
    39
    Rep Power
    0

    Default

    I'm a lit bit afraid to make that change because i have spend a lot of time trying to make it work, and i soon have to give this assignment to my tutor. Isn't there maybe another way where the questions can be generated randomly without making a lot of changes in my program? Thanks a lot. I'm really sorry that i can't follow that advice but i'm a bit afraid of changing it. I wish that i could include a random method in the for loop, that can generate the questions randomly without repeating them. I'm really obliged to both you and Hardwired for helping me. If pls, anyone one of you, knows a shorter way of how to make the questions generated randomly, without having to make a lot of changes in my program, i would really appreciated. Thanks again. :-) And i'm really thankful.

    The for loop:

    Java Code:
    for(int j = 0; j < questions.length; j++) {
                
               timeForMore = true;
               
              
              Random generator = new Random();
              int randomIndex = generator.nextInt(questions.length); 
              String input = JOptionPane.showInputDialog(null, questions[randomIndex]); 
    
            
              if(answers[randomIndex].equalsIgnoreCase(input))
               
               count++;  // incrementing counter if entered answer is correct
               point++;
              
              
          
           
           
           
           
    if(!timeForMore) // if time is over, the program executes the loop an stops asking questions.
                    break; 
         }
             
                
          
                
                 
                JOptionPane.showMessageDialog(null, "You answered " + count +
                                          " out of " + questions.length +
                                          " questions correctly.");
    }
    Last edited by mcal; 01-21-2008 at 10:55 PM.

  20. #20
    tim's Avatar
    tim
    tim is offline Senior Member
    Join Date
    Dec 2007
    Posts
    435
    Rep Power
    7

    Default Random index

    Hello mcal

    That is unfortunate. There is another solution that will needed to be added to this method and it will not require that you alter a lot of your program. You are trying to get a random index, but you repeat indexes. The solution is to create an array, A, that contains the integers of all the indexes possible in incrementing order. Then we create a second array that will contain the final "mixed" indexes, B. Both A and B will need counters to monitor their actual size.
    Now add this code before your for loop:
    Java Code:
    // Create the arrays
    int[] A = new int[questions.length];
    int[] B = new int[A.length];
    // Create the counters
    int countA = A.length;
    int countB = 0;
    // Now add the indexes to A
    for (int i = 0; i < A.length; i++){
        A[i] = i;
    }
    // Now we want to fill up B
    while (countA > 0){
        Random generator = new Random();
        int pos = generator.nextInt(A.length);
        // Add the index of A at pos to B
        B[countB] = A[pos];
        countB++;
        // Remove the index of A at pos from A
        for (int i = pos; i < A.length - 1; i++){
            A[i] = A[i + 1];
        }
        countA--;
    }
    Now we have an array, B, of randomly generated indexes. Inside the for loop that you have created, change this:
    Java Code:
    Random generator = new Random();
    int randomIndex = generator.nextInt(questions.length);
    to this:
    Java Code:
    int randomIndex = B[j];
    This, should do the trick. :p

    I hope this helped. Please ask if there is problems. ;)
    Last edited by tim; 01-22-2008 at 09:56 AM.
    Eyes dwelling into the past are blind to what lies in the future. Step carefully.

Page 1 of 2 12 LastLast

Similar Threads

  1. Loop Help
    By HeavyD in forum New To Java
    Replies: 7
    Last Post: 09-22-2010, 10:55 PM
  2. do...while loop
    By eva in forum New To Java
    Replies: 16
    Last Post: 01-31-2008, 07:44 AM
  3. A loop that doesn't loop
    By MichYer in forum New To Java
    Replies: 2
    Last Post: 07-30-2007, 09:44 AM
  4. While loop
    By leebee in forum New To Java
    Replies: 1
    Last Post: 07-18-2007, 04:11 PM
  5. eternal loop problem
    By sandor in forum New To Java
    Replies: 3
    Last Post: 04-29-2007, 04:55 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
  •