Thread: Random number with a total.

1. Random number with a total.

hey guys.

im making this dicing simulation program.
what it does: it generates a random number when you click the button "hit".
it's in a GUI.

whenever you click the button it creates a random number and displays it, and next to it it displays the total(ill explain later).

the total is: every number generated, added up.

like if you click the button 2 times:
it generates these numbers(example): 14, 86
then i want the total to be: 100.

if you click the button 3 times:
it generates these numbers(example):30, 70, 80
then i want the total to be: 180.

with the current code i have, the total is always equal to the random number generated. (which i dont want..).

i don't really know how to do it.
i tried thinking about a for-loop but i dont know how to put it in that for loop..

so if anyone could help me with this, would be cool.

code:
Java Code:
```final JButton btnRoll = new JButton("Hit");
public void actionPerformed(ActionEvent e) {
Random rand = new Random();
int rand1 = rand.nextInt(100)+1;

lblNewLabel.setText(""+rand1);

int totrand = +rand1;

lblNewLabel_1.setText("Total: "+totrand);

}
});```

2. Senior Member
Join Date
Nov 2010
Posts
167
Rep Power
10

Re: Random number with a total.

It can be more complicated but to keep it simple, try

changing

Java Code:
` int totrand = +rand1;`
to
Java Code:
` int totrand = totrand + rand1;`
I suppose you could also use a loop but I am not sure if that's necessary since you have an ActionListener object...

3. Senior Member
Join Date
Apr 2013
Location
Sweden
Posts
272
Rep Power
8

Re: Random number with a total.

Why would you need a for loop? just as bigsonny said, totrand += rand1;
so each time the button is pressed, the random numbers are added to the sum, which you store in totr

4. Re: Random number with a total.

Originally Posted by superhaNds
Why would you need a for loop? just as bigsonny said, totrand += rand1;
so each time the button is pressed, the random numbers are added to the sum, which you store in totr
well both of your suggestions didnt work.

everytime i click the button, it generates a random number and displays that random number in the total.
but when i click the button again, it does exactly the same.
it doesnt add those 2 numbers.

i cant make it work

5. Re: Random number with a total.

The 'totrand' variable is local to the method in the ActionListener; you get a new one each time that method is called.

Jos

6. Senior Member
Join Date
Apr 2013
Location
Sweden
Posts
272
Rep Power
8

Re: Random number with a total.

yeah sorry, totrand should be declared in class scope.

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•