[英]How to add java.util.Scanner class to read two-dimensional array of float entries input?
我有一个关于使用 java.util.Scanner class 读取浮点条目输入的二维数组的问题,我试图在互联网上找到,但仍然无法工作。 代码向我显示错误。 任何人都可以检查我错了哪一部分? 下面是我的代码:
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!!!");
}
}
}
output 错误如下所示:
C:\Users\User\AppData\Local\NetBeans\Cache\8.0.2\executor-snippets\run.xml:48:
Cancelled by user.
BUILD FAILED (total time: 3 seconds)
实际上我想要 output 显示如下:
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)
访问一个从未定义过的 object, lines
。
float[][] a= new float[5][5];
是声明具有 5 rows
和 5 columns
的二维数组的示例。 float[][] a = new float[][]
不是正确的声明。
您的堆栈跟踪没有提供足够的信息。
Java 的垃圾收集通常会为您关闭Scanner
,在这种情况下您不需要使用sc.close()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.