10/26/2015

IS 4010 Java assignment 3

Problem 1
Create a Die class with one integer instance variable called sideUp. Give it a default constructor and a getSideUp() method that returns
the value of sideUp and a void roll() method that changes sideUp to a random value from 1 to 6. Then create a DieDemo class with a
main method that creates two Die objects, rolls them, and prints the sum of the two sides up. Make sure that name your classes as Die
and DieDemo.

package assignment3;

public class Die {
public int sideUp;
 public Die() {
      this.sideUp = 1;
      }//constructor

public void roll() {
     this.sideUp = (int)(Math.random()*6) + 1;
}
public int getSideUp() {
       return this.sideUp;
   }
 
}

package assignment3;

public class DieDemo {
public static void main( String[] args ) {
        Die D1 = new Die();
        Die D2= new Die();
        System.out.println( D1.getSideUp() );
        D1.roll();
        System.out.println( "D1 is " + D1.getSideUp() );
        D2.roll();      
        System.out.println( "D2 is " + D2.getSideUp() );
        System.out.println("The sum of Die 1 and Die 2 are : " + (D1.getSideUp() + D2.getSideUp()));
    }
 
}

Output:
1
D1 is 6
D2 is 2
The sum of Die 1 and Die 2 are : 8

3 comments: