For this lab, you will be creating an object-oriented (OO) program to play a simple dice game. Start with the following:
Note that to create a class in IntelliJ, right click on the src folder in the project, and select New > Java Class.
In Dice.java, write the Dice class. A Dice object should have two properties/attributes: the number of sides the dice has, and the current value showing on the dice. These properties should be instance variables in your class. Make sure you declare the instance variables private.
Add the following methods:
In the Main class, write the main() method to play a simple game according to the following rules:
Your main method should create variables for the two dice: each should be an object of type Dice.
Your program should ask the user to press the return key before each turn. This can be accomplished with a Scanner object [docs here]. Scanner can be imported with import java.util.Scanner;. For example, you can create a Scanner like this:
Scanner input = new Scanner(System.in);Once you have the scanner initialized like this, you can ask the user for input like this:
System.out.println("Press enter"); String line = input.nextLine();
After each turn, the program should check if we've won. If we've won, print a message saying so and end the program.
In Python, we could give default values to parameters (to constructors or any other methods). In Java, a similar result can be obtained using method overloading: we can have two methods with the same name as long as the parameter lists differ.
Now, go back and modify the Dice class so that when we construct a Dice object without specifying the number of sides, then we get a D6 (but if we do specify a number of sides, then we get a dice with the given number of sides).
Modify main() so it uses this default as appropriate.
Before turning in any program in this class, remember this mantra:
Just because it works doesn't mean it's good.
Part of your grade will also come from things like how understandable and readable your code is. You will also be graded on the neatness, presentation, and style of your program code.
For all labs, turn in only an electronic version. Please compress your program and email the zip file or tarball to me at firstname.lastname@example.org.
Ask for help if you're having problems!