|
|
Welcome to the Java Forums.
You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features. By joining our free community, you will:
- have access to post topics
- communicate privately with other members (PM)
- not see advertisements between posts
- have the possibility to earn one of our surprises if you are an active member
- access many other special features that will be introduced later.
Registration is fast, simple and absolutely free so please, join our community today!
If you have any problems with the registration process or your account login, please contact us.
|
|

01-16-2008, 11:02 PM
|
|
Member
|
|
Join Date: Jan 2008
Posts: 39
|
|
|
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! :-)
|
|

01-16-2008, 11:35 PM
|
 |
Senior Member
|
|
Join Date: Nov 2007
Location: New York
Posts: 143
|
|
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
//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 =]
__________________
//Haha javac, can't see me now, can ya?
|
|

01-16-2008, 11:57 PM
|
 |
Senior Member
|
|
Join Date: Dec 2007
Location: South Africa
Posts: 334
|
|
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. 
__________________
If your ship has not come in yet then build a lighthouse.
|
|

01-17-2008, 12:17 AM
|
|
Member
|
|
Join Date: Jan 2008
Posts: 39
|
|
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:
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:
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.
|
|

01-17-2008, 01:57 AM
|
 |
Senior Member
|
|
Join Date: Nov 2007
Location: New York
Posts: 143
|
|
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.
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
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!
__________________
//Haha javac, can't see me now, can ya?
|
|

01-17-2008, 10:14 AM
|
 |
Senior Member
|
|
Join Date: Dec 2007
Location: South Africa
Posts: 334
|
|
|
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:
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. 
__________________
If your ship has not come in yet then build a lighthouse.
|
|

01-17-2008, 10:23 AM
|
|
Member
|
|
Join Date: Jan 2008
Posts: 39
|
|
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!
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++;
}
|
|

01-17-2008, 10:37 AM
|
 |
Senior Member
|
|
Join Date: Dec 2007
Location: South Africa
Posts: 334
|
|
|
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:
int randomIndex = generator.nextInt(questions.length);
// shows questions in a dialog box together with input line
String input = JOptionPane.showInputDialog(null, questions[randomIndex]);
randomIndex could be some value, A, at some stage, B at another and then A again. The randomIndex idea is unpredictable.
__________________
If your ship has not come in yet then build a lighthouse.
Last edited by tim : 01-17-2008 at 10:41 AM.
|
|

01-17-2008, 11:12 AM
|
|
Member
|
|
Join Date: Jan 2008
Posts: 39
|
|
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!
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 + " % ");
}
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 11:43 AM.
|
|

01-17-2008, 12:21 PM
|
 |
Senior Member
|
|
Join Date: Dec 2007
Location: South Africa
Posts: 334
|
|
|
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.
Questions.txt Answers.txt
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:
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:
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 : - The random factor.
- Questions being repeated.
- Questions having the wrong answers.
I hope this helped. There's a lot of code. (check by hand and likely problematic)
__________________
If your ship has not come in yet then build a lighthouse.
|
|

01-17-2008, 09:09 PM
|
|
Member
|
|
Join Date: Jan 2008
Posts: 39
|
|
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. :-)
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
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
|
|

01-17-2008, 09:28 PM
|
 |
Senior Member
|
|
Join Date: Dec 2007
Location: South Africa
Posts: 334
|
|
|
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.
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. 
__________________
If your ship has not come in yet then build a lighthouse.
|
|

01-17-2008, 09:36 PM
|
|
Member
|
|
Join Date: Jan 2008
Posts: 39
|
|
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. :-)
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
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
|
|

01-17-2008, 09:51 PM
|
 |
Senior Member
|
|
Join Date: Dec 2007
Location: South Africa
Posts: 334
|
|
|
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.
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.
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.
__________________
If your ship has not come in yet then build a lighthouse.
|
|

01-18-2008, 12:01 AM
|
 |
Senior Member
|
|
Join Date: Nov 2007
Location: New York
Posts: 143
|
|
|
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. =]
__________________
//Haha javac, can't see me now, can ya?
|
|

01-18-2008, 12:54 AM
|
|
Member
|
|
Join Date: Jan 2008
Posts: 39
|
|
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.
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.
|
|

01-18-2008, 09:58 AM
|
 |
Senior Member
|
|
Join Date: Dec 2007
Location: South Africa
Posts: 334
|
|
|
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.
try {
BufferedWriter out = new BufferedWriter(new FileWriter("plate_tectonics.dat",true)); // Assuming you want to append to the file
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 /*event*/){
System.out.println("There was a problem: " + e.getMessage());
}
Also, try to use better indentation. It improves the readability of your code.
Hope that helped. 
__________________
If your ship has not come in yet then build a lighthouse.
|
|

01-18-2008, 05:56 PM
|
|
Member
|
|
Join Date: Jan 2008
Posts: 39
|
|
|
Oh thanks a lot.
|
|

01-24-2008, 05:00 AM
|
 |
Senior Member
|
|
Join Date: Nov 2007
Location: New York
Posts: 143
|
|
Originally Posted by tim
Okay mcal.
The QuizProblem class makes things simple as they can get complicated if you use gibsonrocker800 approach.
Damn, i got owned hahah.
__________________
//Haha javac, can't see me now, can ya?
| | |