我有一个关于使用 java.util.Scanner 类读取浮点条目输入的二维数组的问题,我尝试在互联网上找到,但仍然无法工作。代码显示错误。谁能帮我检查一下我哪部分错了?下面是我的代码:
import java.util.Scanner;
public class CloneTwoDarray {
public static float[][] clone(float[][] a) throws Exception {
float b[][] = new float[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
public static void main(String args[]) {
float[][] a = new float[][];
Scanner sc = new Scanner(System.in);
System.out.println("Type nine float numbers two-dimensional array of similar type and size with line breaks, end by \"-1\":");
String append = "";
while (sc.hasNextLine()) {
String input = sc.nextLine();
if ("-1".equals(input)) {
break;
}
lines.add(input);
}
sc.close();
System.out.println("\n\nThe result is:\n");
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
输出错误如下所示:
C:\Users\User\AppData\Local\NetBeans\Cache\8.0.2\executor-snippets\run.xml:48:
Cancelled by user.
BUILD FAILED (total time: 3 seconds)
实际上我希望输出如下所示:
run:
Type nine float numbers two-dimensional array of similar type and size with line breaks, end by"-1":
1.513
2.321
3.421
4.213
5.432
6.123
7.214
8.213
9.213
-1
The result is:
1.513 2.321 3.421
4.213 5.432 6.123
7.214 8.213 9.213
BUILD SUCCESSFUL (total time: 11 second)
希望有人能帮我解决这个问题。谢谢。
最佳答案
我不完全确定您的目标是什么。此外,您还定义了一个从未使用过的方法CloneTwoDarray
。您的行格式需要调整以更具可读性。
至于代码本身,lines.add(input)
访问一个从 undefined object lines
。
float[][] a= new float[5][5];
是声明具有 5 行
和 5 列
的二维数组的示例。 float[][] a = new float[][]
不是正确的声明。
您的堆栈跟踪未提供足够的信息。
Java 的垃圾收集通常会为您关闭 Scanner
,在这种情况下您不需要使用 sc.close()
。
关于java - 如何添加 java.util.Scanner 类来读取浮点条目输入的二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58533191/