我创建了一个程序,根据用户输入的掷骰数掷两次骰子。每两个卷都存储为 x 和 y 值,并插入到二维数组中的相应位置。但是,当骰子重复掷出时,我想不出一个正确的捕捉方法。
数组是这样的:
String [][] arr = {
{"0,0","0,0","0,0","0,0","0,0","0,0"},
{"0,0","0,0","0,0","0,0","0,0","0,0"},
{"0,0","0,0","0,0","0,0","0,0","0,0"},
{"0,0","0,0","0,0","0,0","0,0","0,0"},
{"0,0","0,0","0,0","0,0","0,0","0,0"},
{"0,0","0,0","0,0","0,0","0,0","0,0"}
};
如果骰子输出是: “4和4” “4 和 5” “4 和 4”
然后数组将显示为:
我当前将这些数字插入二维数组的代码如下:
public static String[][] updateArray(String[][] arr, int userInput) {
for (int rolls = 0; rolls < userInput; rolls++) {
int roll1 = rollDice(); // x
int roll2 = rollDice(); // y
String rolled = roll1 + "," + roll2;
System.out.println("The dice rolled: " + roll1 + " and " + roll2);
int xIndex = roll1 - 1;
int yIndex = roll2 - 1;
arr[yIndex][xIndex] = rolled; // first value is y second is x
}
return arr;
}
应该发生的是程序应该发现有一个重复的数字并仅重新滚动这两个特定的滚动以获得没有重复的数组。
我已经尝试了很多复杂的方法,但仍然没有为我工作。我相信有一个更简单的解决方案。如果您需要更多说明,请告诉我。
使用集合来存储已经存在的卷,并使用 while 循环作为重试策略,并在集合包含两个卷的组合时继续调用您的
rollDice()
方法:
public static String[][] updateArray(String[][] arr, int userInput) {
Set<String> set = new HashSet<>();
for (int rolls = 0; rolls < userInput; rolls++) {
int roll1 = rollDice(); // x
int roll2 = rollDice(); // y
String rolled = roll1 + "," + roll2;
while (set.contains(rolled)){
roll1 = rollDice();
roll2 = rollDice();
rolled = roll1 + "," + roll2;
}
set.add(rolled);
System.out.println("The dice rolled: " + roll1 + " and " + roll2);
int xIndex = roll1 - 1;
int yIndex = roll2 - 1;
arr[yIndex][xIndex] = rolled; // first value is y second is x
}
return arr;
}