![](/img/trans.png)
[英]How to add java.util.Scanner class to read two-dimensional array of float entries input?
[英]How to use java.util.Scanner class to read input?
我有一个关于使用 java.util.Scanner class 读取输入的问题。
下面是我的编码,没有使用 java.util.Scanner class 读取输入:
public class NewTry {
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[][] { { 1.513f, 2.321f, 3.421f }, { 4.213f, 5.432f, 6.123f },
{ 7.214f, 8.213f, 9.213f } };
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!!!");
}
}
}
在不使用 java.util.Scanner 的情况下显示 output:
run:
1.513 2.321 3.421
4.213 5.432 6.123
7.214 8.213 9.213
BUILD SUCCESSFUL (total time: 3 seconds)
我的问题是如何在编码中添加 java.util.Scanner class 以读取没有默认浮点数的输入? 是否使用阵列运行扫描仪?
其实我想要的样品 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)
希望有人可以指导我或修改我的编码以添加 java.util.Scanner class 以读取输入。谢谢。
看一下这个
public static void main(String args[]) {
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:");
float[][] a = new float[3][3];
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
String line = sc.nextLine();
if ("-1".equals(line)){
break;
}
a[i][j]=Float.parseFloat(line);
}
}
System.out.println("\n The result is:");
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!!!");
}
}
您应该定义一个新的 Scanner (sc),然后循环 3 x 3 次,直到您读取所有输入。 如果用户输入 -1,则循环结束。 请注意,输入 9 个数字时无需退出。
此外,每个用户输入都被读取为一行而不是一个标记,然后被解析为一个浮点数。 如果用户输入的字符串不是浮点数,则会引发异常。
样本:
Type nine float numbers two-dimensional array of similar type and size with line breaks, end by -1:
1.1
1.2
1.3
2.1
2.2
2.3
3.1
3.2
3.3
The result is:
1.1 1.2 1.3
2.1 2.2 2.3
3.1 3.2 3.3
Scanner scan =new Scanner(System.in);
float[][] a = new float[3][3];
for(int i =0 ;i<3;i++) {
for(int j=0; j<3; i++) {
a[i][j] =scan.Float();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.