介绍
我正在做一些作业,我们的任务是制作寻找对子的游戏。我做了一个矩阵,并用这样的字母填充它:
Display
----------------
C H F E
G F D D
E C H B
A B G A
现在,我目前正在测试显示方法,该方法使用一个空矩阵并用给定的输入填充 (row_1, col_1, row_2, col_2, gameMatrix)
问题
同时创建“作弊/测试功能”以测试我的显示方法。我在查找两个A(或其他任何字母)的位置时遇到了一些麻烦。这是我尝试的这种方法:
码
public static void PlayMeBoi(String[][] gameMatrix)
{
int row_1 = 0;
int col_1 = 0;
int row_2 = 0;
int col_2 = 0;
for (int i = 0; i < gameMatrix.length; i++)
{
for (int j = 0; j < gameMatrix.length; j++)
{
if ("A".equals(gameMatrix[i][j]))
{
row_1 = i;
col_1 = j;
break;
}
}
}
for (int i = (row_1+1); i < gameMatrix.length; i++)
{
for (int j = (col_1+1); j < gameMatrix.length; j++)
{
if ("A".equals(gameMatrix[i][j]))
{
row_2 = i;
col_2 = j;
break;
}
}
}
System.out.println("First " + gameMatrix[row_1][col_1] + " at " + " [ " + row_1 + " ] " + "," + " [ " + col_1 + " ] ");
System.out.println("Second " + gameMatrix[row_1][col_1] + " at " + " [ " + row_2 + " ] " + "," + " [ " + col_2 + " ] ");
Turn(row_1, col_1, row_2, col_2, gameMatrix);
}
有关代码的注释
if "A".equals("A")
)的函数(row_1+1)
和(col_1+1)
这是我的想法,在“如果我没有发现我的信之前,那么第二个‘的’将处理矩阵的其余部分)gameMatrix
是加载所有字母的矩阵题
我希望能够找到矩阵中“ A”或任何其他字母的位置。截至目前,我目前的想法还没有达到我想要的结果
随意评论代码。我可能会在以后将它发布在GitHub上,供有兴趣或发现有用内容的人使用。
感谢您对此问题的关注。
如果我以前没有找到我的字母,那么第二个“ for”将处理矩阵的其余部分
正确,但是矩阵的其余部分到底是什么?
如果A
在row = 1
和中找到第一个col = 1
,则矩阵的其余部分是每个带有索引的项目> 1
。这将删除索引为(1,2),(2,1)和(1,3)等的项目。
还有其他问题。
当您将一个break
嵌套循环放入一个嵌套循环中时,它只会从嵌套循环而不是外部循环中中断。
这是我想出的一个解决方案,也许它不是最佳解决方案,但我认为它可行:
public static void PlayMeBoi(String[][] gameMatrix) {
int row_1 = -1;
int col_1 = -1;
int row_2 = -1;
int col_2 = -1;
boolean found = false;
for (int i = 0; i < gameMatrix.length; i++) {
if (found) break;
for (int j = 0; j < gameMatrix[0].length; j++) {
if ("A".equals(gameMatrix[i][j])) {
row_1 = i;
col_1 = j;
found = true;
break;
}
}
}
if (!found) {
System.out.println("Not Found");
return;
}
found = false;
for (int i = 1; i < gameMatrix.length; i++) {
if (found) break;
for (int j = 1; j < gameMatrix[0].length; j++) {
if (i * gameMatrix[0].length + j > row_1 * gameMatrix[0].length + col_1) {
if ("A".equals(gameMatrix[i][j])) {
row_2 = i;
col_2 = j;
found = true;
break;
}
}
}
}
System.out.println("First " + gameMatrix[row_1][col_1] + " at " + " [ " + row_1 + " ] " + "," + " [ " + col_1 + " ] ");
if (!found) {
System.out.println("Second Not Found");
return;
}
System.out.println("Second " + gameMatrix[row_1][col_1] + " at " + " [ " + row_2 + " ] " + "," + " [ " + col_2 + " ] ");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句