簡體   English   中英

如何添加 java.util.Scanner class 來讀取浮點條目輸入的二維數組?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM