【问题标题】:Boolean unique dice布尔唯一骰子
【发布时间】:2018-05-08 03:30:29
【问题描述】:

我有一个骰子类,可以滚动 1-6 的随机数。我想创建另一个类来实现检查所有数字并在所有唯一数字滚动一次时停止滚动。不知道如何使用 getFace 和 boolean 方法。考虑从 false 开始的每个数字,一旦数字出现,结果为 true。

public class Die {

public final int MAX = 6; //max 6
private int faceValue; //current value showing on die

//constructor
public Die() {
   faceValue = 1;
   }

public int roll(){
  faceValue = (int)(Math.random()*MAX)+1;
  return faceValue;
  }

public void setFaceValue(int value){
  if(value> 0 && value <=MAX)
     faceValue=value;
  }

public int getFaceValue(){
  return faceValue;
  }

public String toString(){
  String result = Integer.toString(faceValue);
  return result;
  }
}

【问题讨论】:

  • 可能以SetList 开头,其中填充了唯一的数字。使用getFaceValue 删除List 中的值,一直滚动直到它为空
  • 将面值添加到集合中,当集合大小为 6 时停止滚动。在点名中 setFaceValue 将面值添加到集合中。创建一个布尔方法来检查 Set 的大小并返回 true 或 false。
  • 没学过set,就跟list一样?

标签: java arrays boolean


【解决方案1】:
ArrayList<Integer> numList = new ArrayList<Integer>();
//Add 1-6
for(int i = 1;i < 7;i++){
    numList.Add(i);
}
Die dice = new Die();
While(numList.size() != 0){
   int rolled = dice.roll();
   ArrayList.remove(rolled);
}

我假设代码是这样的。好久没接触java了。

【讨论】:

  • 如何使用另一个测试类对其进行测试?只需创建一个骰子对象和 dice.roll?
  • @WickdLotus 您应该能够在 main 方法中运行它。像 public static void main(string[] args){//code here 和一些 writeline}
  • 还在学习类我要创建一个实例并在另一个类中测试它,也许把所有这些都放在公共空白中?
  • 是的,我认为这在另一个类方法中是可能的,但您仍然必须在主方法中的某个地方调用该方法。您可以在当前类的主方法中创建用于测试目的的实例并运行它。
【解决方案2】:

逻辑: 创建一个集合 S。继续滚动并将结果添加到该集合。当集合的大小为 6 时停止。(集合仅包含唯一元素。)

import java.util.HashSet;
import java.util.Set;

public class Play {

    public static void main(String[] args) {

        Die die = new Die();
        Set<Integer> set = new HashSet<>();
        int outcome = 0;

        //Keep rolling until set size is 6.
        while(set.size() != 6) {
            outcome = die.roll();
            set.add(outcome);
        }

        System.out.println(set);

    }

}

class Die {

    public final int MAX = 6; //max 6
    private int faceValue; //current value showing on die

    //constructor
    public Die() {
        faceValue = 1;
    }

    public int roll(){
        faceValue = (int)(Math.random()*MAX)+1;
        return faceValue;
    }

    public void setFaceValue(int value){
        if(value> 0 && value <=MAX)
            faceValue=value;
    }

    public int getFaceValue(){
        return faceValue;
    }

    public String toString(){
        String result = Integer.toString(faceValue);
        return result;
    }
}

【讨论】:

  • 有道理,但我还没有学习 hash sets 数组列表会相似吗?
  • 由于 ArrayList 允许重复,您可以检查列表是否已经包含“结果”。如果没有,请将其添加到列表中。其余代码将保持不变。
猜你喜欢
  • 1970-01-01
  • 2016-03-13
  • 1970-01-01
  • 1970-01-01
  • 2016-01-31
  • 1970-01-01
  • 2018-09-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多