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