I am having a problem with the below applet. It compiles just fine and when it is ran it shows up with the multiplication problem at the bottom of the applet as expected. The problem is that it says if the answer is correct or not before an answer is input. After I input an answer it doesn't seem to check that either. I know it has something to do with the boolean statements but I can't seem to adjust it to work properly. Any help would be great.

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
public class multiplicationGame extends JApplet implements ActionListener 
{ 
int num1, num2;
int random;
int answer;
JTextField guess = new JTextField(4); // Holds the answer the player will enter
JLabel message = new JLabel("Type your answer and press enter: "); // JLabels to hold messages to output on the screen.
JLabel message2 = new JLabel(" ");
boolean correct = false;
boolean question = true;



public void init()
{
Container con = getContentPane();
setLayout(new FlowLayout());
add(message);
add(guess);
add(message2);
guess.addActionListener(this);

}

public void paint(Graphics g)
{
if(question == true)
{
super.paint(g);
newQuestion();
boolean question = false;
}


if( correct == true)
{
message2.setText("Very good!");
newQuestion();
}
else
{ 
message2.setText("No. Please try again.");
}
}

public void actionPerformed(ActionEvent event)
{


int answer = Integer.parseInt(guess.getText());

if(answer == random)
{
boolean correct = true;
}
else
{
boolean correct = false;
}
repaint();
}

public void newQuestion()
{
int num1 = 1 + (int)(Math.random() * 9);
int num2 = 1 + (int)(Math.random() * 9);
int random = num1 * num2;
showStatus("How much is " + num1 + " times " + num2 + ".");
}

}

Recommended Answers

All 3 Replies

You really don't want to put any program logic in a paint(Graphics g) method because you have no way of knowing when or how often it will be called. The actionListener is generally a far better place for it.

So you are suggesting something like this then?

public void actionPerformed(ActionEvent event)
{  
int answer = Integer.parseInt(guess.getText()); 

if(answer == random)
{
message2.setText("Very good!");
newQuestion();
}
else
{
message2.setText("No. Please try again.");
}
repaint();
}

Then scrap the paint method and just place a call to the newQuestion() method under the init() method? Can't test it until I get home tonight.

Yes, try that. There's no need for paint(...) unless you are doing custom graphics of some sort.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.