骰子修改
经过对Java中面向对象的理解,重新对骰子进行修改,仅保留了一般功能!
Test类:
import java.util.Scanner; public class Test { public static void main(String[] args) { int num; System.out.println("请输入骰子的个数:"); @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); num = sc.nextInt(); Cup cup = new Cup(num); cup.rollPrint(); } }
Cup类:
public class Cup { private int num; @SuppressWarnings("unused") private Dice[] dice; public Cup(int num) { this.num = num; dice = new Dice [num]; for(int i = 0; i < num; i++) { dice[i] = new Dice(); } } public void setNum(int num) { this.num = num; } public int getNum() { return num; } public void rollPrint() { for(int i = 0; i < num; i++) { System.out.print("第" + (i+1) + "个骰子的面值:" + dice[i].getFaceValue()); System.out.println(); } } }
Dice类:
public class Dice { private int faceValue; public Dice() { faceValue = (int)(Math.random() * 6) + 1; } public int getFaceValue() { return faceValue; } }
运行结果: