Results 1 to 5 of 5
Thread: classes and creating objects
- 11-01-2010, 03:34 PM #1
Member
- Join Date
- Oct 2010
- Posts
- 25
- Rep Power
- 0
classes and creating objects
Create a Dice class that has a face data field (that indicates the current value showing). The class should have a getFace method which returns the current value of face, and a roll method that chooses a random value for face. Write a main program that creates 2 Dice objects. The main program should roll both dice and display the value showing for each. Be sure to use proper style. Create a jar file of your program and attach to this assignment page.
This is what I have:
Is this correct?Java Code:public class Dice { int face = 6; // returns the current value of face int getFace() { return face; } int roll() { return 1 + (int)(Math.random() * 7); } } public class diceGame { public static void main(String[] args) { Dice dice1 = new Dice(); System.out.println("dice1 is " + dice1.getFace()); Dice dice2 = new Dice(); System.out.println("dice2 is " + dice2.roll()); } }Last edited by Latanyar; 11-01-2010 at 04:28 PM.
-
No, it's not correct. The roll() method should change face and that's it. It shouldn't return an int. Rather the result of the roll is obtained by calling getFace(). And your formula for rolling is not right as it will allow a result of 7 (check it and see).
Also, you will want to test your code to find out best if it works or not.
- 11-01-2010, 04:26 PM #3
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
<pedant>...and it's Die not Dice in the singular...</pedant>
;)
- 11-01-2010, 07:10 PM #4
Member
- Join Date
- Oct 2010
- Posts
- 25
- Rep Power
- 0
-
The instructions pretty much spell out what's needed. Let's see your latest code.
Similar Threads
-
Assign objects to classes
By dellacpa in forum New To JavaReplies: 4Last Post: 08-02-2010, 09:27 PM -
Classes and Objects Help
By collin389 in forum New To JavaReplies: 1Last Post: 12-14-2009, 12:44 AM -
Constructors Objects and Classes
By Tykk in forum New To JavaReplies: 4Last Post: 10-10-2009, 11:31 PM -
classes as objects
By kroiz in forum New To JavaReplies: 4Last Post: 07-25-2009, 05:22 AM -
Objects and Classes
By Aleve in forum New To JavaReplies: 8Last Post: 12-31-2007, 08:05 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks