gpt4 book ai didi

带有二维数组的 Java 程序

转载 作者:行者123 更新时间:2023-12-01 07:27:15 27 4
gpt4 key购买 nike

我正在编写一个程序,决定数字 X 是否位于输入 n x n 数字矩阵的矩阵中,该数字已以 2D 数组形式存储在内存中,并且每个单独的行从左到右递增;列从上到下。我输入矩阵n的大小、内容以及要搜索的数字X;我还在屏幕上显示搜索结果。在测试我的程序时,我的输入按二维数组排序。

这是我的代码,它显示以下编译错误

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)

最佳答案

您在 main() 内部有 search 方法,它应该在外部。此外,您还在 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);
}

关于带有二维数组的 Java 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22305207/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com