Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Sum not returning correctly

1. ## Sum not returning correctly

There's this program I have to write for school:
Craps is a popular dice game played in casinos. Write a program to play a
variation of the game, as follows:
Roll two dice. Each die has six faces representing values 1, 2,…, and 6,
respectively. Check the sum of the two dice. If the sum is 2, 3, or 12 (called
craps), you lose; if the sum is 7 or 11 (called natural), you win; if the sum is
another value (i.e., 4, 5, 6, 8, 9, or 10), a point is established. Continue to roll
the dice until either a 7 or the same point value is rolled. If 7 is rolled, you lose.
Otherwise, you win. The program should contain a method:
public static int getDice() {}
The method returns the value of the sum of the two dice.

My code so far is as follows:
```import java.util.Random;

public class Craps
{
public static void main(String[] args)
{
System.out.println("You rolled " + d1() + " + " + d2() + " = " + getDice());

}//end main method

public static int getDice(){
int sum = d1() + d2();
return sum;
}//end getDice()
public static int d1(){
Random myGenerator = new Random();
int d1 = myGenerator.nextInt(6) + 1;
return d1;
}//end d1()
public static int d2(){
Random myGenerator2 = new Random();
int d2 = myGenerator2.nextInt(6) + 1;
return d2;
}//end d2()

}//end class```

My sum is completely different to what it should be. I know the problem is that I'm calling the method 2 different times which is giving me a random number for each of the calls but I can't think up a solution to solve it. Any help would be appreciated.

2. ## Re: Sum not returning correctly

try this buddy...

public static void main(String[] args)
{
int d1 = Craps.d1();
int d2 = Craps.d2();
System.out.println("You rolled " + d1 + " + " + d2 + " = " + getDice(d1,d2));

}//end main method

public static int getDice(int d1,int d2){
int sum = d1+d2;
return sum;
}//end getDice()
public static int d1(){
Random myGenerator = new Random();
int d1 = myGenerator.nextInt(6) + 1;
return d1;
}//end d1()
public static int d2(){
Random myGenerator2 = new Random();
int d2 = myGenerator2.nextInt(6) + 1;
return d2;
}//end d2

}

3. ## Re: Sum not returning correctly

Thanks man I can't believe I didn't think of that.