Results 1 to 19 of 19

Thread: Random problem

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

    Default Random problem

    Hey Guys,

    I have a problem about how to generate randomly when the data consists of string and not integers. I wish to display a set of questions, which are stored in the textfile randomly. How can i do it? I know that i have to use the Math.Random but i don't know how to apply it since my data is string (since it is questions) and not numbers. If you can, pls can you give me an example using source code. Thanks a lot! :-)

  2. #2
    gibsonrocker800's Avatar
    gibsonrocker800 is offline Senior Member
    Join Date
    Nov 2007
    Location
    New York
    Posts
    143
    Rep Power
    0

    Default

    Hm, well, when you read in the questions, you can store them in a String array, and, you can make it generate a String with a random index. For example

    Java Code:
    //Read in questions and store them to String[] questions
    Random generator = new Random();
    int randomIndex = generator.nextInt(questions.length); 
    //Generate a random number, and the maximum number it can be
    //is the number of questions there are
    
    System.out.println(questions[randomIndex]);
    Hope that helps =]

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

    Default

    Hello mcal.

    I can remember someone asking a question very similar to yours. I answered it and it has methods that you might find useful. One such method in one that can mix an array randomly, to prevent repetitions in the questions. Have a look at this tread.

    I hope this helped. :D
    Eyes dwelling into the past are blind to what lies in the future. Step carefully.

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

    Default

    Yeah it worked. Thanks a lot. My problem is now with the answers. Because, now that the questions come up randomly, the way that the answers are stored, the questions will be generated incorrectly since they won't match the answer. I have stored the answers of the questions in an array. What can i do? Thanks a lot.

    This is the code used for the random questions:

    Java Code:
    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]); // shows questions in a dialog box together with input line
                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; 
         }

    And this is the code where my answers are stored:

    Java Code:
    class AnswerStore  {  // storing answers of each quiz in arrays
        String[] tectonicAnswers = {
            "Ben", "Henry", "Duncan", "Elaser", "Wegner",
            "Maria", "Susan", "Dudley", "Fanny", "Martin"
        };
    Thanks again for the help.

  5. #5
    gibsonrocker800's Avatar
    gibsonrocker800 is offline Senior Member
    Join Date
    Nov 2007
    Location
    New York
    Posts
    143
    Rep Power
    0

    Default

    Well there are several approaches to this problem. Personally, i would make a method called public int checkAnswers(String[] userAnswers)
    It returns the number of questions they got right.

    So now, in this method we would define the correct answers, and check if the user's answers equal the correct answers.

    Java Code:
    public int checkAnswers(String[] userAnswers)
    {
         String[] tectonicAnswers = {
            "Ben", "Henry", "Duncan", "Elaser", "Wegner",
            "Maria", "Susan", "Dudley", "Fanny", "Martin"
        };
         int correct = 0;
         
         for(int i = 0; i < tectonicAnswers.length; i++)
         { 
              if(userAnswers[i].equalsIgnoreCase(tectonicAnswers[i])
                    correct++;
         }
    
         return correct;
    }
    So, in the tester class, when we read in the users answers as a String array, we will pass the aforementioned array to checkAnswers. So you could do

    Java Code:
    String[] answers = //however you are going to read in their answers.
    System.out.println("You got " + (whatever the object name is).checkAnswers(answers) + " correct!");
    Now, you should try to make this more sophisticated. You have it return which questions they get wrong, and an explanation why the correct answer is what it is. Good luck man!

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

    Default Oop

    Hello gibsonrocker800 and mcal.

    Java is an Object Orientated Language. Why not use this to our advantage for this problem. ;) Let's create a class that contains the question, answer and some functionality:
    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 you can create an array of QuizProblem objects and call it Quiz. You can modify the array mix method to work with the QuizProblem class or use generics if you want to. This way, you do not have to worry about data being lost or corrupted because of a changing data structure.

    I hope this helped. :D
    Eyes dwelling into the past are blind to what lies in the future. Step carefully.

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

    Default

    Yeah i have understood. Thanks a lot Man! I just got one last problem. My problem is that altough my program is popping up random questions, the problem is that it is sometimes displaying the same questions, since it is displaying them randomly. What can i do? Thanks a lot again! ;)

    Java Code:
     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]); // shows questions in a dialog box together with input line
            
             
            
              if(answers[randomIndex].equalsIgnoreCase(input))
               
              count++;  
               point++;
              
         }

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

    Default Mix method

    I am sorry if I am repeating myself, but in the code I provided, the questions are loaded first, then you mix it using the mix method and then you can use the questions in incrementing order. That will prevent repetitions of the questions. The problem in your code lies here:
    Java Code:
    int randomIndex = [COLOR="Blue"]generator.nextInt(questions.length)[/COLOR]; 
    // shows questions in a dialog box together with input line
    String input = JOptionPane.showInputDialog(null, questions[[COLOR="Blue"]randomIndex[/COLOR]]);
    randomIndex could be some value, A, at some stage, B at another and then A again. The randomIndex idea is unpredictable.
    Last edited by tim; 01-17-2008 at 09:41 AM.
    Eyes dwelling into the past are blind to what lies in the future. Step carefully.

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

    Default

    Oh i understood. Thanks. I tried doing it like this, (similar to the one were you posted to the other question) but its still not working, since its displaying some of the questions repeatedly. Do i have something wrong? Thanks a lot Man!

    Java Code:
      public void askQuestions(String[] questions, String[] answers) {
          
            int count = 0;
            int point = 0;
            
            
           for(int j = 0; j < questions.length; j++) {
                
               timeForMore = true;
               
              
             
               
        Vector<String> data = loadFile("quiz2.txt");
        int pos = (int)((double)data.size() * Math.random());
      String input = JOptionPane.showInputDialog(null, data.get(pos));
               
              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 " + questions.length +
                                          " questions correctly.");
                int percent = (count*100)/questions.length;
            JOptionPane.showMessageDialog(null, "Your  Quiz score is " + percent + " &#37; ");
               
        
               
              
             
              
          }
          
         public static Vector<String> loadFile(String filename){
        Vector<String> strings = new Vector<String>();
        try{
            FileReader file = new FileReader("quiz2.txt");
            BufferedReader buffer = new BufferedReader(file);
            while (true)
            {
                String line = buffer.readLine();
                if (line == null)
                    break;
                else {
                    strings.add(line); 
                }
            }
            buffer.close();
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
        return strings;
    }
    
    
    class AnswerStore  {  // storing answers of each quiz in arrays
        String[] quiz1Answers = {
            "Yes", "No", "yes", "Yes", "No", "yes", "Yes", "No", "yes"
            "Yes", "No", "yes", 
          
        };
        
        String[] quiz2Answers = {
           yes", "Yes", "No", "yes", "Yes", "Yes", "No", "yes"
            "Yes", "No"
    
        };
        
        String[] quiz3Answers = {
           yes", "Yes", "No", "yes", "Yes", "Yes", "No", "yes"
            "Yes", "No"
        };
    
    
         }
    
    }
    Thanks again. :)
    Last edited by mcal; 01-17-2008 at 10:43 AM.

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

    Default Mixing data structures

    Okay mcal.

    You are mixing data structures and your code presents problems for the future. The QuizProblem class makes things simple as they can get complicated if you use gibsonrocker800 approach. Lets stick with vectors as they have less limitations. You will need to use the QuizProblem class to prevent the question/answer mismatch problem. So lets put all your questions in one file and answers in another.
    Java Code:
    [B]Questions.txt				Answers.txt[/B]
    How did the skeleton cross the road?	He didn't - cause he had no guts!
    Do spiders breath through their mouths?	No.
    And so on...				And so on...
    Now we can modify the load method to create QuizProblem objects from the two files:
    Java Code:
    public static Vector<QuizProblem> loadFile(String questions, String answers){
        Vector<QuizProblem> quiz = new Vector<QuizProblem>();
        try{
            FileReader questionsFile = new FileReader(questions);
            BufferedReader questionsBuffer = new BufferedReader(questionsFile);
            FileReader answersFile = new FileReader(answers);
            BufferedReader answersBuffer = new BufferedReader(answersFile);
            while (true)
            {
                String question = questionsBuffer.readLine();
                String answer = answersBuffer.readLine();
                if ((question == null) || (answer == null))
                    break;
                else {
                    quiz.add(new (question, answer)); 
                }
            }
            questionsFile.close();
            answersFile.close();
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
        return quiz;
    }
    And we will need a mix method for QuizProblem objects later:
    Java Code:
    public static Vector<QuizProblem> mix(Vector<QuizProblem> quiz){
        Vector<QuizProblem> data = new Vector<QuizProblem>();
        Vector<QuizProblem> result= new Vector<QuizProblem>();
        data = new Vector<QuizProblem>(quiz);
        int count = 0;
        while (data.size() > 0){
            int pos = (int)(Math.random() * (double)data.size());
            QuizProblem next = data.get(pos);
            result.set(count++, next);
            data.remove(pos);
        }
        return result;
    }
    From somewhere in your program you can call these methods like this:
    Vector<QuizProblem> quiz = mix(loadFile("questions.txt", "answers.txt"));
    Now, you can ask each question in its order in the vector and not worry about:
    1. The random factor.
    2. Questions being repeated.
    3. Questions having the wrong answers.

    I hope this helped. There's a lot of code. :D (check by hand and likely problematic)
    Eyes dwelling into the past are blind to what lies in the future. Step carefully.

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

    Default

    Ok thanks a lot. I have another problem. I have to use a binary file (instead of textfiles) to store (write) a the questions, which then i have to read using GUI. I have written one question on this binary file, but for the other 10 questions i have to do the same thing like the following code and if so can you pls tell me how to write the second question because when i tried doing it like the first one, it only showed me the first question. Thanks a lot. :-)

    Java Code:
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.DataOutputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
     
    public class BinaryFileOutput
    {
       public static void main( String[] args )
          throws FileNotFoundException, IOException
       {
          // declare and initialize variables
         
          
          String name   = "What are the mainn sources of energy?";
        
       
         
     
          File aFile  = new File( "personal.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( name );
     
        
          aFileOutStream.close();
     
       } // end main
     
    } // end class
    Java Code:
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.DataInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
     
    public class BinaryFileInput
    {
       public static void main( String[] args )
          throws FileNotFoundException, IOException
       {
          // declare and initialize variables
          String name;
         
     
          File aFile  = new File( "personal.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 );
     
          // read data from file
          name   = aDataInStream.readUTF();
          
          aFileInStream.close();
     
          // output
          System.out.println( name + "\t");
     
       } // end main
     
    } // end class

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

    Default binary files

    Hello mcal

    You can create an object that can contain all your questions and answers. Then you can let it implement the Serializable interface. Now, using an ObjectInputStream or an ObjectOutputStream, you can easily save or load the object in one line of code.

    Quote Originally Posted by mcal
    I have to use a binary file
    Is this an assignment? You need to try and learn how to analyze your own code logically.

    I will explain Object streaming if you want me to do that. ;)
    Eyes dwelling into the past are blind to what lies in the future. Step carefully.

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

    Default

    Thanks a lot. Yeah this is an assignment, an the teacher told me instead of using a textfile i should use a binary file. And now i got a bit confused, because i have to alter everything. I had written the questions in a textfile, and now my teacher told me that i should write them on a binary file. And i don't know how to write multiple lines on a binary file. I had succesfully achieved in displaying a single question but i need to display the others. I did something like this. I am on the right track? It is issuing an EOFexception error. Thanks again for your help. :-)

    Java Code:
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.DataOutputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
     
    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.*;
     
    public class BinaryFileOutput
    {
       public static void main( String[] args )
          throws FileNotFoundException, IOException
       {
          // declare and initialize variables
         
          
          String name   = "What are the mainn sources of energy?";
          String name2 =   "Who are you?";
          String name3 =   "Who are you?";
        
       
         
     
          File aFile  = new File( "personal.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( name );
          aDataOutStream.writeUTF( name2 );
           aDataOutStream.writeUTF( name3 );
     
    aDataOutStream.close();
        
          aFileOutStream.close();
     
       } // end main
     
    } // end class
    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.FileInputStream;
    import java.io.DataInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
     
    public class BinaryFileInput
    {
       public static void main( String[] args ) 
          throws FileNotFoundException, IOException, EOFException
       {
          // declare and initialize variables
          String name;
          String name2;
          String name3;
         
     
          File aFile  = new File( "personal.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 );
     
          // read data from file
          name   = aDataInStream.readUTF();
          name2   = aDataInStream.readUTF();
          name3   = aDataInStream.readUTF();
         String[] questions= name.split("\\?");
         
          aFileInStream.close();
     
            
          // output
           System.out.println( name + "\t"+ name2);
           
        
     
       } // end main
     
    } // end class

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

    Default Looks okay

    It looks fine to me. Try to use data structures and loops now. Repeating code and creating variables for each data element is not a solution for loading or saving a file.
    Quote Originally Posted by mcal
    And i don't know how to write multiple lines on a binary file.
    You do not have to worry about "lines" when using the DataInputStream or the DataOutputStream.
    Quote Originally Posted by mcal
    It is issuing an EOFexception error
    You must let your code "try" (by using a try-catch block) to read the data until this exception is thrown, then you can stop reading and continue with your program.

    Also, it is not a good idea to let your main() method throw Exception objects. You must catch the exceptions yourself and respond to them appropriately.
    Eyes dwelling into the past are blind to what lies in the future. Step carefully.

  15. #15
    gibsonrocker800's Avatar
    gibsonrocker800 is offline Senior Member
    Join Date
    Nov 2007
    Location
    New York
    Posts
    143
    Rep Power
    0

    Default

    I wish i could help here, but i'm not too educated on binary files. I read about them but never really fully understood them. Listen to tim, he knows what he's talking about. =]

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

    Default

    Ok thanks. Just one last problem. Since before i was using a textfile i used the Buffered Reader. But now i have to use DataOutputStream and FileOutputStream. I have a little problem with this code, because i don't know how to change it so that it would write to a binaryfile. Can you pls help me out? Thanks a lot, and i'm really sorry if i have bothered you. I have tried many times to change it but i really can't do it. Thanks again.


    Java Code:
      try {
                
                         BufferedWriter out; // what do i have to write her instead of Buffered Reader
                         String text = JOptionPane.showInputDialog(null, "Enter new question");
                         out = new BufferedWriter(new FileWriter("plate_tectonics.dat",true));
                  
                        out.write(text); //Writing to the textfile (the name entered by user)
                        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 event){
                       System.out.println("There was a problem:" + e);
    
                                   }
    Thanks again.

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

    Default indentation and minor errors

    Hello

    Your code is correct except for the event part. It should be a "e" and the getMessage() call is missing.
    Java Code:
    try {
        [COLOR="Teal"]BufferedWriter out = new BufferedWriter(new FileWriter("plate_tectonics.dat",true)); // Assuming you want to append to the file[/COLOR]
        String text = JOptionPane.showInputDialog(null, "Enter new question");
        out.write(text); //Writing to the textfile (the name entered by user)
        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 [COLOR="Red"]/*event*/[/COLOR]){
        System.out.println("There was a problem: " + e.[COLOR="Blue"]getMessage[/COLOR]());
    }
    Also, try to use better indentation. It improves the readability of your code.

    Hope that helped. ;)
    Eyes dwelling into the past are blind to what lies in the future. Step carefully.

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

    Default

    Oh thanks a lot.

  19. #19
    gibsonrocker800's Avatar
    gibsonrocker800 is offline Senior Member
    Join Date
    Nov 2007
    Location
    New York
    Posts
    143
    Rep Power
    0

    Default

    Quote Originally Posted by tim View Post
    Okay mcal.

    The QuizProblem class makes things simple as they can get complicated if you use gibsonrocker800 approach.
    Damn, i got owned hahah.

Similar Threads

  1. random numbers without random class`
    By carlos123 in forum New To Java
    Replies: 4
    Last Post: 01-17-2008, 10:44 PM
  2. random generation
    By carlos123 in forum New To Java
    Replies: 10
    Last Post: 01-09-2008, 03:43 AM
  3. random numbers
    By carlos123 in forum New To Java
    Replies: 1
    Last Post: 12-22-2007, 02:56 AM
  4. Random Integers
    By www.kwalski.com in forum Java Applets
    Replies: 8
    Last Post: 12-09-2007, 05:49 PM
  5. getting a random result
    By gradon in forum New To Java
    Replies: 2
    Last Post: 07-19-2007, 03:54 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
  •