我正在写一个程序,决定数字X是否在数字的输入nxn矩阵的矩阵中,该矩阵已经存储在2D数组的存储器中,并且每个单独的行从左到右增加; 从上到下的列.我输入矩阵n的大小,内容和要搜索的数字X; 我还在屏幕上显示我的搜索结果.在测试我的程序时,输入按2D数组排序.
这是我的代码,它显示了以下编译错误
import java.util.*;
public class matrix
{
public static void main (String[] args){
int search(int mat[4][4]; int n; int x)
{
int i = 0, j = n-1; //set indexes for top right element
while ( i < n && j >= 0 )
{
if ( mat[i][j] == x )
{
printf("\n Found at %d, %d", i, j);
return 1;
}
if ( mat[i][j] > x )
j--;
else // if mat[i][j] < x
i++;
}
printf("\n Element not found");
return 0; // if ( i==n || j== -1 )
}
// driver program to test above function
int main()
{
int mat[4][4] = { {10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50},
};
search(mat, 4, 29);
return 0;
}
}
}
Run Code Online (Sandbox Code Playgroud)
堆栈跟踪:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on token "(", ; expected
Syntax error on token "4", delete this token
Syntax error on token "4", delete this token
Syntax error on token ")", ; expected
The method printf(String, int, int) is undefined for the type matrix
Void methods cannot return a value
The method printf(String) is undefined for the type matrix
Void methods cannot return a value
Syntax error on token "int", new expected
main cannot be resolved to a type
Syntax error, insert ";" to complete FieldDeclaration
Syntax error, insert "}" to complete ClassBody
Syntax error on token "}", delete this token
at matrix.main(matrix.java:8)
Run Code Online (Sandbox Code Playgroud)
你有search里面的方法main(),它应该在外面.此外,您main在main()方法中声明了另一个.请记住,main方法是程序的入口点,应该只存在一个:
public static void main(String[] args) { ... }
Run Code Online (Sandbox Code Playgroud)
在Java中,您不应该在参数声明中声明数组的长度.另外,使用逗号分隔参数:
public static int search(int[][] mat, int n, int x)
Run Code Online (Sandbox Code Playgroud)
你应该使用System.out.printf()而不是仅仅printf().
最后,可以通过多种方式声明/初始化数组:
int mat[][] = {{1,2}, {3,4}};
int mat[][] = new int[3][3];
int mat[][] = new int[3][];
Run Code Online (Sandbox Code Playgroud)
最终代码应如下所示:
public static int search(int[][] mat, int n, int x)
{
int i = 0, j = n - 1; //set indexes for top right element
while (i < n && j >= 0) {
if (mat[i][j] == x) {
System.out.printf("\n Found at %d, %d", i, j);
return 1;
}
if (mat[i][j] > x) {
j--;
} else {
i++;
}
}
System.out.printf("\n Element not found");
return 0; // if ( i==n || j== -1 )
}
public static void main(String[] args)
{
int mat[][] = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 27, 29, 37, 48 }, { 32, 33, 39, 50 }, };
search(mat, 4, 29);
}
Run Code Online (Sandbox Code Playgroud)