|
|
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-19-2008, 09:48 PM
|
|
Member
|
|
Join Date: Jan 2008
Posts: 39
|
|
|
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:
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", "",
"", ""
};
}
}
|
|

01-19-2008, 10:16 PM
|
|
Senior Member
|
|
Join Date: Jul 2007
Posts: 1,124
|
|
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");
}
}
|
|

01-19-2008, 10:29 PM
|
|
Member
|
|
Join Date: Jan 2008
Posts: 39
|
|
|
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.
|
|

01-20-2008, 02:26 AM
|
|
Senior Member
|
|
Join Date: Jul 2007
Posts: 1,124
|
|
Did you see the example in Data Streams?
|
|

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

01-20-2008, 07:49 PM
|
|
Senior Member
|
|
Join Date: Jul 2007
Posts: 1,124
|
|
the for loop isn't working
Let's have a look at the askQuestions method.
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
// stopAndShowResults method by another class.
// If you set it to true 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]);
the counter isn't being incremented
// There are no curley braces after this if
// statement to form a code block so the next statement,
// viz, "count++;", is the only statement affected/protected
// by this if statement. If you add a curley brace
// after the if statement and after the "point++"
// statement then boith statements will be
// included_in/controlled_protected_by the if 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:
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.
|
|

01-20-2008, 08:18 PM
|
|
Member
|
|
Join Date: Jan 2008
Posts: 39
|
|
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:
askQuestions(questions, answers);
it just skips the for loop and continues displaying the others:
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 + " % ");
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:
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.
|
|

01-20-2008, 09:06 PM
|
|
Senior Member
|
|
Join Date: Jul 2007
Posts: 1,124
|
|
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.
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:
private void askQuestions(String[] questions, String[] answers) {
System.out.printf("questions = %s%nanswers = %s%n", // debugging
Arrays.toString(questions),
Arrays.toString(answers));
|
|

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

01-20-2008, 09:52 PM
|
|
Senior Member
|
|
Join Date: Jul 2007
Posts: 1,124
|
|
|
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.
|
|

01-20-2008, 09:58 PM
|
|
Senior Member
|
|
Join Date: Jul 2007
Posts: 1,124
|
|
|
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.
|
|

01-20-2008, 10:53 PM
|
|
Member
|
|
Join Date: Jan 2008
Posts: 39
|
|
|
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.
|
|

01-21-2008, 06:15 PM
|
| | |