Home > Computer Programming > Dice game in Java

Dice game in Java

package sampleprogram;
import java.util.Random;
import java.util.Scanner;

public class DiceGame {

public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  int sides;
  int numDice;

  System.out.println("How many sides for the dice?");
  sides = in.nextInt();
  System.out.println("How many dice?");
  numDice = in.nextInt();
  System.out.println();

  Die[] dice = new Die[numDice];

  for(int i = 0; i < numDice; i++){
    dice[i] = new Die();
    dice[i].setSides(sides);
    dice[i].roll();
    System.out.print(dice[i].getValue() + " ");
  }

  System.out.println();
  }
}

class Die{
  private int sides;
  private int value;
  private Random r = new Random();

  void setSides(int sides){
    this.sides = sides;
  }

  void roll(){
    value = r.nextInt(sides) + 1;
  }

  int getValue(){
    return value;
  }
}
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s