java - 打印二维数组中值的位置

标签 java arrays search

我定义了一个二维数组,其中包含一些整数。在我的程序中,用户输入一个数字以在二维数组中搜索它。找到数字后,我想打印该数字在数组中的位置。但在我的程序中,它无法打印 j 的位置。我该如何纠正它?

public static void main(String[] args) {
   int[][] arrayOfInt = {
       {12, 14, 15},
       {56, 36, 48},
       {23, 78, 69,48}
   };
   Scanner input = new Scanner(System.in);
   int search,i,j;
   boolean check = false;
   System.out.print("Enter your number: ");
   search = input.nextInt();
   search:
   for (i=0; i<arrayOfInt.length; i++)
   {
       for(j=0; j<arrayOfInt[i].length; j++)
       {
           if(arrayOfInt[i][j] == search)
           {
               check = true;
               break search;
           }
       }
   }
   if (check)
   {
        System.out.println("i = " + i + " and j = " + j);
   }
   else
   {
       System.out.println("There is not in the array!");
   }
}

最佳答案

编译器提示 j 未初始化,因为只有执行外部 for 循环的内容时才会为其赋值。

您可以通过将 j 初始化为任意值来消除此错误,如下所示:

int search, i, j = -1;

关于java - 打印二维数组中值的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22279527/

相关文章:

java - 如何计算按Java8流中的属性分组的对象中的多个总和?

C 返回重复字符的数量

关于使用扩展运算符包含 1...N 的数组的 Javascript 异常行为

sql-server - SQL Server : Search all tables for a particular GUID

java - 在 JfreeChart 中绘制模糊阴影?

java - hibernate 中的魔法 npe

java - Firebase 中的嵌套列表

c++ - 如何在 void 函数内正确动态分配二维数组?

python - 哪种算法可以更快地对这些数字对进行排序?

android - 我如何使用 baseadapter 过滤 ListView