Click to See Complete Forum and Search --> : Chance Game Java: Need Help Getting it To Run


coder752
July 24th, 2009, 12:05 PM
I need help, it won't run. It only prints my message I put in main. What's wrong? Please help.

It compiles fine, and it just gives me an exception in thread "main" error.



import java.util.Random;

public class Dice{


//create random number generator for roling the dice.
private Random random = new Random();

//enumeration with constants that stand for the game status
private enum Status{CONTINUE, WON, LOST};

//simulates a game of craps
public void play(){

Status gameStatus; //Can contain CONTINUE, WON, or LOST
int myPoint = 0; //Point if user doesn't win or lose on first try.

//srand((unsigned)time(NULL));
int sum=TwoDice();

// Cases determined on first roll.
switch(sum)
{
case 7:
case 11:
gameStatus=Status.WON;
break;

case 2:
case 3:
case 12:
gameStatus=Status.LOST;
break;

default: //for cases if there's no win or lose yet.
gameStatus=Status.CONTINUE; //game continues.
myPoint=sum; //remembers the point
} //end of switch

//while game is not finished yet.
while(gameStatus==Status.CONTINUE){
sum=TwoDice(); //Rolls dice again.

//Finds out game status once more.
if(sum == 7)
gameStatus=Status.LOST;
else
if(sum == myPoint)
gameStatus=Status.WON;

}
if (gameStatus==Status.WON)
System.out.println("Player wins");
else
System.out.println("Player loses");
} //end of play
//Sum of the dice.
public int TwoDice(){
//Get random dice values.
int die1 = 1+random.nextInt(6); //first die roll
int die2 = 1+random.nextInt(6); //second die roll
int sum = die1+die2; //sum of die values

//Prints the results of this roll.
System.out.println("Player rolled: "+die1 +die2);
System.out.println("Sum is: " +sum);
return sum;
}//end of TwoDice

public static void main(String[]args){
System.out.println("Craps Simulator");
}
} //end of Dice

Xeel
July 24th, 2009, 12:49 PM
changed to:public static void main(String[] args) {
System.out.println("Craps Simulator");
Dice dice = new Dice();
dice.play();
}

output:Craps Simulator
Player rolled: 44
Sum is: 8
Player rolled: 62
Sum is: 8
Player wins

Works pretty fine for me...

Your problem is not in the code as I understand. Could you post the whole exception?

coder752
July 24th, 2009, 01:13 PM
I understand my mistake now, it's because I didn't create a new dice, and I also didn't call the play method.

Now it works.

So no worries.

Thanks

= D