如何添加java.util.Scanner类以读取浮点输入的二维数组?

问题描述 投票:1回答:1

我有一个关于使用java.util.Scanner类读取浮点输入的二维数组的问题,我试图在Internet上找到它,但是仍然无法正常工作。该代码向我显示了错误。任何人都可以为我检查我错了哪一部分?下面是我的代码:

    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) 

希望有人可以帮助我解决这个问题。谢谢。

java arrays
1个回答
0
投票

我不确定您的目标是什么。另外,您定义了永远不会使用的方法CloneTwoDarray。您需要调整行格式以提高可读性。

关于代码本身,lines.add(input)访问从未定义的对象lines

float[][] a= new float[5][5];是声明5 rows和5 columns的二维数组的示例。 float[][] a = new float[][]不是正确的声明。

您的堆栈跟踪没有提供足够的信息。

Java的垃圾回收通常会为您关闭Scanner,在这种情况下您无需使用sc.close()

© www.soinside.com 2019 - 2024. All rights reserved.