Hi,
I writing a "Math Game program" which does the follow:
Generate random two operand problems.
Allow to the user to enter the solution
Each time the user gets a correct result then display a random encouraging message. Similar for incorrect attempts.
This program works good in BlueJ, BUT when I write those codes in NetBeans, My problems are:
The two random operands always start with 0.
If statement don't get the properly result.
I set the For loop in 3, but it don't end.
Any suggestions would be great.
Thank you.
[code]import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Game extends Applet implements ActionListener {
Label prompt;
TextField input;
int numb1;
int numb2;
int player;
int answer;
Label status;
public void init()
{
prompt = new Label( "What is " + numb1 + " + " + numb2 + "?" );
add( prompt );
input = new TextField( 10);
add( input );
input.addActionListener( this );
status = new Label("Status");
add(status);
}
public void paint (Graphics g)
{
setBackground (Color.ORANGE);
}
public void actionPerformed( ActionEvent e )
{
for ( int i = 1; i<= 3; i++ )
{
numb1 = (int)(Math.random()*10)+1;
numb2 = (int)(Math.random()*10)+1;
prompt.setText( "What is " + numb1 + " + " + numb2 + "?");
player = Integer.parseInt(e.getActionCommand());
input.setText("");
answer = (numb1 + numb2);
if (player == answer)
{
status.setText("Excelent");
}
else
{
status.setText("Incorrect answer, please try again");
}
}
repaint();
}
}
[/code]
Comments
Math.random() may return 0 and give a predictable sequence of numbers because it may start with the same random seed.
This is similar to the problem of getting the same sequence of random numbers in a c program by calling rand() without calling srand().
The Random class from java.util package allows you to make an instance and set the "random seed".
Regarding the for-loop seeming to be unending, how do you know it doesn't end?
Assuming you just aren't seeing all the values
Check the Java console for stack traces of exceptions.
It seems like there may be an exception thrown in there that is causing you to not see a result.
Do you get NumberFormatException or NullPointerException? If there is a printout of a stack trace, what does it trace show?