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.

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();
    }
}

First: the init() method is the equivalent of a constructor for an applet, as such it gets called first. Since you don't initialize your numbers before using them in the labels, Java takes them as 0 and displays it that way.

Second: the problem lies in your actionPerformed method. The user types something and hits enter, your actionPerformed method is called. Instead of first checking if the user gave the correct answer, you first change the numbers, and check afterwards if the user gave the correct answer to a question he couldn't see when he answered. Unless by chance you generate numbers that give the same answer, the user will always have the wrong answer, thereby never getting through your if statement. And why is there a for loop? Since the user can't try another time (you just use e.getActionCommand(), which doesn't change if your loop), the loop just checks something 3 times without anything having changed.

Lastly: What do you mean with "doesn't end"? Are the sentences of your if-else statement being printed constantly or is nothing happening? Put some System.out.printlns in your code to see where the program is at various stages.

is that a problem? I don't really check the forum at java-forums, and I assume there will be more members who don't.

No problem. Just trying to save people time by showing other posts of this question by the OP.

Lastly: What do you mean with "doesn't end"?

I mean for loop doesn't work properly because repeat random question, more than 3 times.

the loop just checks something 3 times without anything having changed.

Those codes work well, but I need add a for loop in order to repeat the question to user 3 times. I'm not sure if add the for loop in "resetLabel()" or "actionPerformed"
Thank you.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
 
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( "");

        add( prompt );

        resetLabel();
 
        input = new TextField( 10);
        add( input );
 
        input.addActionListener( this );
 
        status = new Label("Status");
        add(status);
    }

private void resetLabel()
    {
        numb1 = (int)(Math.random()*10)+1;
        numb2 = (int)(Math.random()*10)+1;
        answer = numb1 + numb2;
        prompt.setText( "What is " + numb1 + " + " + numb2 + "?");

    }

public void actionPerformed( ActionEvent e )
    {
        player = Integer.parseInt(input.getText());

        input.setText("");
 
        if (player == answer)
        {
            status.setText("Excelent");
            resetLabel();
            input.setText("");
        }

        else
        {
            status.setText("Incorrect answer, please try again");      
        }  
    }
}

To count the number of times the user pressed Enter you need to have a counter variable at the class level that you increment every time the user presses Enter and goes to the actionPerformed method.

to repeat the question to user 3 times

You can NOT loop inside of that method because it is called in response to the user's pressing Enter. The "loop" needs to consider all the events that you want to happen in the "loop": Show numbers, get user response, test response and display results.
You can NOT get a new user response while in the actionPerformed method. You must exit and wait for the user to enter the new number and press Enter.

Since you're making a program which responds to the user doing things, instead of the user doing things the program tells it to do, a for loop is not very apropriate here. A normal say console program, is one thread, your code is executed 'top to bottom'. An applet waits for the user to do something and then reacts to it.

As NormR1 said, keep a variable that you increment each time the actionPerformed gets called, and at the end of that method, you check to see if the number of tries has been reached, and your program can respond to it.

keep a variable that you increment each time the actionPerformed gets called, and at the end of that method, you check to see if the number of tries has been reached, and your program can respond to it.

Can you explain me this in more details showing me codes, please?

define an int at the class level:

int tryCount = 0;      // counts number of user tries

in the actionPerformed method:

...
  tryCount++;  ?? count the number of tries
  if(tryCount > MaxNbrTries) {  // test if max tries done yet
      // Do what you want when max # exceeded
  }

I've add a "paint class" which draw a smile face every time the user types the correct answer, but it doesn't work.
I made some print lines and I could see this

ans = 11play =0 // 4+7 answer's(11) is display before user(player)add a number, showing the smile face.
ans = 19play =11 // when user(player) adds the answer(11) answer add the answer of the next addition question 10+9.

I also made some print lines in "actionPerformed class" on if statement and I could see this.

ans = 12play =12 // the user(player) adds answer (12) and answer is display
ans ok // player has answer(12) correctly the answer.

I added repaint() in "actionPerformed class" as well.

public void paint(Graphics g) {

       //System.out.println("ans = " + answer + "play =" + player);

        if (player == answer)//Draw a smile face every time answer is correct
   
         //System.out.println("ans ok");
       {
            g.drawOval(150, 85, 71, 90);
            g.drawArc(170, 130, 30, 30, 0, -180);
            g.drawOval(172, 118, 10, 10);
            g.drawOval(190, 118, 10, 10);
            g.setColor(Color.white);
        }
}
public void actionPerformed(ActionEvent e)
       {
        player = Integer.parseInt(input.getText());
        input.setText("");

        System.out.println("ans = " + answer + "play =" + player);
       
        if (player == answer)
        {   
            System.out.println("ans ok");
            
            status.setText("Excellent");
            resetLabel();
            input.setText("");
             
        }
        else {
            status.setText("Incorrect answer, please try again");
        }
         repaint();
       }

Any suggestion to solve the problem? Thank you for your help in advance.

Can you post the complete code for the version you are now working with?
Its hard to tell what your program is doing with only these small bits of code.

Can you post the complete code for the version you are now working with?
Its hard to tell what your program is doing with only these small bits of code.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;

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("");
        add(prompt);
        resetLabel();

        input = new TextField(10);
        add(input);

        input.addActionListener(this);


        status = new Label("Status Here");

        add(status);
    }

    private void resetLabel() 
    {
        numb1 = (int) (Math.random() * 10) + 1;
        numb2 = (int) (Math.random() * 10) + 1;
        answer = numb1 + numb2;
        
        
        prompt.setText("What is " + numb1 + " + " + numb2 + "?");
    }

    public void paint(Graphics g) 
    {
       setBackground(Color.red);
       System.out.println("ans = " + answer + "play =" + player);
       
        if (player == answer)//Draw a smile face every time answer is correct 
        
          System.out.println("ans ok");

        {
            g.drawOval(150, 85, 71, 90);
            g.drawArc(170, 130, 30, 30, 0, -180);
            g.drawOval(172, 118, 10, 10);
            g.drawOval(190, 118, 10, 10);
            g.setColor(Color.white);
        }
    }

    public void actionPerformed(ActionEvent e) 
   {
        player = Integer.parseInt(input.getText());
        input.setText("");
        
       System.out.println("ans = " + answer + "play =" + player);
      
        if (player == answer)
        {    
            System.out.println("ans ok");
            status.setText("Excellent");
            resetLabel();
            input.setText("");
            
        } 
        else {
            status.setText("Incorrect answer, please try again");
        }
      
        repaint();
    }
}

What is supposed to happen when I execute the code and type in a number and press enter?
If what I type in is correct, "Excellent" is displayed and "ans ok" is printed on console.
If it is not correct, "incorrect answer" is displayed. Nothing is printed on the console.

The happy face is always shown.

Look at your logic to see why the "ans ok" message is printed in one case and not printed in another.
Then look at when the happy face is drawn.

Look at your logic to see why the "ans ok" message is printed in one case and not printed in another.
Then look at when the happy face is drawn.

Yes, But do you know how to fix it?

Your code always draws the happy face. Change the logic of the code so that it only draws the face when you want it drawn instead of always drawing it.

What is supposed to happen when I execute the code and type in a number and press enter?
If what I type in is correct, "Excellent" is displayed and "ans ok" is printed on console.
If it is not correct, "incorrect answer" is displayed. Nothing is printed on the console.

The happy face is always shown.

Look at your logic to see why the "ans ok" message is printed in one case and not printed in another.
Then look at when the happy face is drawn.

The happy face's supposed to show after the user (player) adds the correct answer and press Enter.
But appears before the user(player) adds any number.

Your code always draws the happy face. Change the logic of the code so that it only draws the face when you want it drawn instead of always drawing it.

Ok, but how can I change the logic of the codes?

One problem debugging your code is that your printlns do not show where there are being printed. You should change the text of what is printed out so that you know exactly which println printed it.
When you change the printlns so you can see which one printed you will see that there is a problem with when you set values and when you test them.
Then you will have to think about the how your application works to be sure the variables have the right values when you test them.

One problem debugging your code is that your printlns do not show where there are being printed. You should change the text of what is printed out so that you know exactly which println printed it.
When you change the printlns so you can see which one printed you will see that there is a problem with when you set values and when you test them.
Then you will have to think about the how your application works to be sure the variables have the right values when you test them.

Printlns were just for testing the problem, I just used printlns in paint() class, because I know the problem is there.
what do you mean about...

the variables have the right values when you test them.

Could you explain me this in codes, please?

When you print out the values of variables as the program executes you will see that some of them change before you want that to happen.
Change the printlns as I suggested so you can tell where each of them are printed, execute the program and enter one correct answer and press Enter. Stop the prograam and
Copy the full contents of the print outs here and I will show you where the problem is.

Copy the full contents of the print outs here and I will show you where the problem is.

public void paint(Graphics g) 
{
  System.out.println("Smile Face: Player Answer= " + player + " Answer= " + answer);
       
        if (player == answer)//Draw a smile face every time answer is correct in addition
        {
            System.out.println("Smile Face: Player Answer Ok");
            g.drawOval(150, 85, 71, 90);
            g.drawArc(170, 130, 30, 30, 0, -180);
            g.drawOval(172, 118, 10, 10);
            g.drawOval(190, 118, 10, 10);
            g.setColor(Color.white);
        }
        else 
        {
            System.out.println("Confirm answer:");
            System.out.println("Player Answer Not Ok");
            g.drawOval(150, 85, 71, 90);
            g.drawArc(170, 130, 30, 30, 0, 180);
            g.drawOval(172, 118, 10, 10);
            g.drawOval(190, 118, 10, 10);
            g.setColor(Color.white);
        }
}
public void actionPerformed(ActionEvent e) 
{
       System.out.println("If Statement:");
       System.out.println("Player Answer= " + player + " Answer= " + answer);
        if (player ==  answer)
        {    
           System.out.println("Confirm answer:");
           System.out.println("Player Answer Ok");
            status.setText("Excellent");
            resetLabel();
            input.setText("");
        } 
        else 
        {
            System.out.println("Confirm answer:");
            System.out.println("Player Answer Not Ok");
            status.setText("Incorrect answer, please try again");
            
        }
}

Is this the way you want the printlns?
Thanks.

Close. On this line you label two values to be Answer. The first value is Player:
System.out.println("Player Answer= " + player + " Answer= " + answer);
vs
System.out.println("Player= " + player + " Answer= " + answer);

What prints out when you execute the program?

Close. On this line you label two values to be Answer. The first value is Player:
System.out.println("Player Answer= " + player + " Answer= " + answer);
vs
System.out.println("Player= " + player + " Answer= " + answer);

What prints out when you execute the program?

[TEX]Player Answer= 11 Answer= 11[/TEX]

This means player (the user) type its answer of e.g. what is 5 + 4?
answer (the answer generated by the program) e.g. answer = numb1 + numb2(numb1 & 2 are a random numbers generated by the program)it's like to show the solution.

You need to show ALL Of the numbers your program is using when it uses them.
The print out you posted only shows the values at one place. What about when the values are changed to new values in other places?
For example in the resetLabel method.

You need to show ALL Of the numbers your program is using when it uses them.
The print out you posted only shows the values at one place. What about when the values are changed to new values in other places?
For example in the resetLabel method.

[TEX]
What is 3 + 6?[/TEX]

[TEX]Smile Face: Player Answer= 0 Answer= 9[/TEX]

[TEX]Confirm answer:[/TEX]

[TEX]Player Answer Not Ok[/TEX]

[TEX]Smile Face: Player Answer= 0 Answer= 9[/TEX]

[TEX]Confirm answer:[/TEX]

[TEX]Player Answer Not Ok[/TEX]

[TEX]If Statement:[/TEX]

[TEX]Player Answer= 9 Answer= 9[/TEX]

[TEX]Confirm answer:[/TEX]

[TEX]Player Answer Ok[/TEX]

[TEX]What is 7 + 3?[/TEX]

[TEX]Smile Face: Player Answer= 9 Answer= 10[/TEX]

[TEX]Confirm answer:[/TEX]

[TEX]Player Answer Not Ok[/TEX]

This is all.

Does the program work correctly now?
Looking at your posting of print outs:
Where is the variable: answer given a value? Where does your code compare answer with what the user typed in?

Does the program work correctly now?
Looking at your posting of print outs:
Where is the variable: answer given a value? Where does your code compare answer with what the user typed in?

It doesn't work. The first print out of the face gives answer value before let the user type. That why I don't understand, how to sort it.
Please if you know how to fix it, let me know.
Thanks

Think about what order the events are happening.
When does the code set the values of numb1 and numb2 and answer?
When does the user enter his value?
When are those two values (the user's entry and the answer amount) compared?

Is the value of answer that is being compared to the user's input the correct one for the pair of numbers that the user saw or is it the value for the next pair of numbers?

Your print outs should show you what order they are done in.

Think about what order the events are happening.
When does the code set the values of numb1 and numb2 and answer?
When does the user enter his value?
When are those two values (the user's entry and the answer amount) compared?

Is the value of answer that is being compared to the user's input the correct one for the pair of numbers that the user saw or is it the value for the next pair of numbers?

Your print outs should show you what order they are done in.

It's being compared the value for the next pair of numbers, instead of compare the user's input.

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.