1.11M Members

Maths random number

 
0
 

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

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.

 
0
 

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.

 
0
 

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

 
0
 

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");      
        }  
    }
}
 
0
 

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.

 
0
 

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.

 
0
 

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?

 
0
 

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
  }
 
0
 

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.

 
0
 

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.

 
0
 

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

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.

 
0
 

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?

 
0
 

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.

 
0
 

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.

 
0
 

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?

 
0
 

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.

 
0
 

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?

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article