如何在2D数组中捕获重复的字符串值并替换它



我创建了一个程序,根据用户输入的掷骰子次数掷两次骰子。每两个滚动都被存储为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和5"4 ">

则数组将显示为:

二维阵列输出

将这些数字插入2D数组的当前代码如下:

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;
}

应该发生的是,程序应该发现有一个重复的数字,并且只滚动这两个特定的数字,以得到一个没有重复的数组。

我已经尝试了许多复杂的方法,但仍然不适合我。我相信有一个更简单的解决办法。如果您需要进一步的说明,请告诉我。

const UserInput = null;
int intNumOfDoubles = null;
int[][] intDiceRollsArr = {
{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}, {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}, {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}
};
public static int[][] updateArray(int[][] intDiceRollsArr, int userInput) {
for (int rolls = 0; rolls < userInput; rolls++) {
UserInput = userInput
int roll1 = rollDice(); // x
int roll2 = rollDice(); // y

System.out.println("The dice rolled: " + roll1 + " and " + roll2);
int xIndex = roll1 - 1;
int yIndex = roll2 - 1;
intDiceRollsArr[rolls][xIndex] = roll1;
intDiceRollsArr[rolls][yIndex] = roll2;
}   
return intDiceRollsArr;
}
public static void CheckDoubles(int[][] intDiceRollsArr){
boolean boolIsMoreRolled = true;
while(boolIsMoreRolled == true){
for(int intCounter = 0; intCounter < UserInput; intCounter++){
if(intDiceRollArr[intCounter][1] == 0){
boolIsMoreRolled = false;
} 
else{
if(intDiceRollArr[intCounter][0] == intDiceRollArr[intCounter][1]){
intNumOfDoubles++;
}
}
}
}
}

最新更新