simple looping problem

This is a seemingly simple problem, but I cannot seem to figure out why the total variable is not summing the two die results.

Any help would be appreciated. Here is the code:

public class Die2 extends Object {

public Die2() {

}

public static void roll(){

for(int i=0; i<=2;i++){

int result=(int)(Math.random()*6)+1;

int total=+result;

if (i!=2)

System.out.println("You rolled: " + result);

else

System.out.println("Total roll is " + total);

}

}

public static void main (String args[]) {

Die2 die=new Die2();

die.roll();

}

}

[657 byte] By [susandenise1] at [2007-9-26 1:25:54]
# 1
You are re-defining the total on each loop ...declare the total variable outside of the loop...
FelipeGaucho at 2007-6-29 1:08:05 > top of Java-index,Archived Forums,Java Programming...
# 2
Yes, but then I will not be able to access the local variable result.
susandenise1 at 2007-6-29 1:08:05 > top of Java-index,Archived Forums,Java Programming...
# 3
yes you will, within the for loop.
parthasarkar at 2007-6-29 1:08:05 > top of Java-index,Archived Forums,Java Programming...
# 4

Yes they are right, you must declare the total out of the loop. Besides that : int total=+result is not the same as adding the value of result to the total variable, it is actually setting total to the value of result.

Finally, if you make roll() static you don't need to do a new Die2(). You can just call roll like this : Die2.roll();

esmo at 2007-6-29 1:08:05 > top of Java-index,Archived Forums,Java Programming...
# 5
Thanks everyone!
susandenise1 at 2007-6-29 1:08:05 > top of Java-index,Archived Forums,Java Programming...
# 6
Andtotal=+result;should betotal += result;?
Hartmut at 2007-6-29 1:08:05 > top of Java-index,Archived Forums,Java Programming...