Java - 循环2d数组以查找值不起作用的索引 [英] Java - Looping 2d Array to find index of a value not working

查看:130
本文介绍了Java - 循环2d数组以查找值不起作用的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我在这段代码的某个地方犯了一个错误,但我无法弄明白。 player1.getId();返回值1只是为了让您知道。我正在尝试打印值为1的数组的索引。在代码的最后,我期望currentX为0,currentY为0,但它们都是9.任何帮助都是超级的。

I know I'm making an error somewhere in this code, but I can't figure it out. The player1.getId(); returns a value of 1 just so you are aware. I'm trying to print the index of the array where the value is 1. At the end of the code, I expected currentX to be 0 and currentY to be 0, but they were both 9. Any help would be super.

int[][] grid = {
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3}
};

int currentX = 0;
int currentY = 0;

grid[0][0] = player1.getId();

grid[0][9] = 2;

for (int i = 0; i < grid.length; i++) {
    for (int j = 0; j < grid[0].length; j++) {
        if (grid[i][j] == player1.getId());
        {
            currentX = i;
            currentY = j;
        }
        System.out.print(grid[i][j]);
    }

}
System.out.println();
System.out.println("Player1 is currently in row " + currentX + " and column " + currentY);


推荐答案

删除分号(; )在结束时if(grid [i] [j] == player1.getId());

考虑如何工作如果 java声明

Consider how works if statement of java

如果 if 语句的表达式是 true,则如果 java语句执行它的块代码。半冒号结束了java的声明。如果在if语句之后放入空的半冒号,则将其视为空语句。所以, if 语句在执行 if 语句时什么也不做,结尾有半冒号。 Java编译器按如下方式编译代码。

The if statement of java executes it's block code if the expression of if statement is true. Semi colon ends a statement of java. If you put empty semi colon after if statement it counts as an empty statement. So, if statement does nothing when executing if statement which having semi colon at the end. Java compiler compiles your code similarly as follows.

if (grid[i][j] == player1.getId()){
    //nothing here
}

{
    currentX = i;
    currentY = j;
}

看看当其他类型的声明最后有半冒号时会发生什么。


  • ,而循环

  • while loop

    while (expression);
    {
        //something goes here 
    }


初始化 true 或 false > while 循环。如果条件是 true ,则会产生无限循环。在线后没有任何东西会执行。如果表达式是 false ,它将执行一次的预期内容,而循环。

The condition can be true or false when initializing while loop. If the condition is true it makes an infinite loop. Nothing will execute after the line. If expression is false, it executes once the expected content of while loop.


  • switch(整数); catch(例外e);

无法编译并获得异常 {预计

这篇关于Java - 循环2d数组以查找值不起作用的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆