Answer to Question #278692 in Java | JSP | JSF for Hab1bti

Question #278692

1.



Create a file called



Die.java


, with an empty class in it.



2.



Add a new (private) field to the class to store the number of sides. You probably want this to



be an



int


.



3.



Create



a



constructor



for



Die



that



takes



one



argument,



an



int



representing



the



number



of



sides.



If the number is less than 2, store 6 as the number of sides in the class field.



Other-



wise, store the number given.



4.



Create a no-argument constructor.



It should assume the number of sides is six.



You can do



this in one line with the



this()



constructor, but that isn’t required to get full credit.



5.



Add a



roll()



method to your



Die


, which takes no arguments and returns an



int



between 1



and the number of sides (inclusive).



1
Expert's answer
2021-12-12T12:19:46-0500


import java.util.Scanner;


class Die {
	private int numberSides;


	public Die() {
		this.numberSides = 6;
	}


	public Die(int numberSides) {
		if (numberSides < 2) {
			this.numberSides = 6;
		} else {
			this.numberSides = numberSides;
		}
	}


	public int roll() {
		return (int) (Math.random() * numberSides) + 1;
	}
}


public class App {


	/**
	 * The start point of the program
	 * 
	 * @param args
	 * 
	 */
	public static void main(String[] args) {
		Scanner keyBoard = new Scanner(System.in);
		System.out.print("Enter the number of sides: ");
		int numberSides = keyBoard.nextInt();
		Die die = new Die(numberSides);


		System.out.println(die.roll());
		keyBoard.close();
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS