【问题标题】:printing the location of a value in a two dimensional array打印二维数组中值的位置
【发布时间】:2014-03-09 07:26:48
【问题描述】:

我定义了一个包含一些整数的二维数组。在我的程序中,用户输入一个数字以在二维数组中搜索它。找到数字后,我想打印数组中数字的位置。但在我的程序中,它无法打印 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!");
   }
}

【问题讨论】:

  • 为什么需要search:
  • @MarounMaroun,一旦找到j,它就是一个打破外循环的标签
  • @svz 是的,我知道,但这里是多余的。
  • @MarounMaroun 为什么它是多余的?

标签: java arrays search


【解决方案1】:

编译器抱怨j 没有被初始化,因为它只有在外部for循环的内容被执行时才会被赋值。

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

int search, i, j = -1;

【讨论】:

    【解决方案2】:

    您的程序看起来不错,应该没有任何问题。

    唯一的事情是,您需要打印 i+1 和 j+1 值才能打印数组的实际索引。另外,您需要在开头初始化 j。

    int search,i,j = 0;
    
    if (check)
    {
         System.out.println("i = " + (i+1) + " and j = " + (j+1));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      • 2015-02-03
      • 2018-12-02
      • 1970-01-01
      相关资源
      最近更新 更多