My applet calculates two random numbers and lets the user insert a number. The computer checks whether the answer is correct or not, and then writes an appropriate string in the applet.
However, I have two problems:
a) I cannot call method startGame() from init(). Is that normal? If so, what can be done to call methods in the init() method?
b) When I call repaint(), the drawString does not correctly print the message I want. However, the System.out.println's just before repaint(), the same conditionals occur and the message is displayed correctly. I think that might be because repaint() is called too late once the variables' values have been changed? But I'm not sure
I would really appreciate if someone could help me. Thank you very much for reading this.
Code:
import java.awt.*;
import java.applet.Applet;
public class Operaciones extends Applet
{
/* GUI Varibles: *
* 1. start Button: Starts game *
* 2. answerText TextField: Inputs answer */
Button start;
TextField answerText;
/* User interactive Variables: *
* 1. response: Gets answer from answerText */
int answer = 0;
/* Non-user Variables: *
* 1. numA: Generates a random number *
* 2. numB: Generates a random number *
* 3. correct: Says if answer is correct or not */
int numA;
int numB;
boolean correct = false;
boolean firstTime = true;
public void init()
{
answerText = new TextField(10);
answerText.setEditable(false);
start = new Button("Start / New!");
add (answerText);
add (start);
}
public boolean action(Event e, Object o)
{
if (e.target == answerText) /* User wants to check an answer *
* methods called to verify existing answers */
{
repaint();
answer = Integer.parseInt(o.toString());
correct = checkGame(answer);
}
else /* User wants to start a new game */
startGame();
return true;
}
public void paint(Graphics g)
{
if (correct & !(firstTime))
g.drawString("Correct! You did it!", 25, 125);
else if (!(correct) & !(firstTime))
g.drawString("Try again!", 25, 125);
}
public void startGame()
{
numA = (int) (Math.random() * 100);
numB = (int) (Math.random() * 100);
showStatus("How much is " + numA + " times " + numB + " ?");
correct = false;
answerText.setEditable(true);
}
public boolean checkGame(int checkAnswer)
{
firstTime = false;
if (numA * numB == checkAnswer)
correct = true;
if (correct & !(firstTime))
System.out.println("Correct! You did it!");
else if (!(correct) & !(firstTime))
System.out.println("Try again!");
repaint();
try
{
Thread.sleep(100000);
}
catch (InterruptedException e)
{
};
if (correct)
startGame();
else
showStatus("ERROR: Try again. How much is " + numA + " times " + numB + "?");
return correct;
}
}