编写一个程序,决定数字X是否在输入矩阵n x n数字矩阵中,该矩阵已经存储在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;
}
}
}
堆栈追踪:
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)
答案 0 :(得分:6)
search
中有main()
方法,它应该在外面。此外,您在main
方法中声明了另一个main()
。请记住,main方法是程序的入口点,应该只存在一个:
public static void main(String[] args) { ... }
在Java中,您不应该在参数声明中声明数组的长度。另外,使用逗号分隔参数:
public static int search(int[][] mat, int n, int x)
您应该使用System.out.printf()
而不只是printf()
。
最后,可以通过多种方式声明/初始化数组:
int mat[][] = {{1,2}, {3,4}};
int mat[][] = new int[3][3];
int mat[][] = new int[3][];
最终代码应如下所示:
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);
}
答案 1 :(得分:1)
据我所知,Java不支持本地函数,这就是编译器被抛弃的原因。当然,使用';'分离函数参数也无济于事。
public static void main (String[] args){
int search(int mat[4][4]; int n; int x) // Local method declaration.