2017-10-08 28 views
-1

具有包含具有固定的行和列的二維數組的文本文件[6] [3]爪哇 - 文本至2D陣列刪除空格」

a 5 7 
b 9 7 
c 1 0 
d 0 5 
e 8 7 
f 0 4 

我需要把數據放入陣列playerOne[][]

這是我的代碼

try { 
     Scanner sc = new Scanner(new File("test.txt")); 
     while (sc.hasNextLine()) { 
      for (int i = 0; i < 6; i++) { 
       for (int j = 0; j < 3; j++) { 
        String line = sc.next().trim(); 
        if (line.length() > 0) { 
         playerOne[i][j] = line; 
         System.out.println(i+ " " +j+ " "+ line); 
        } 
       } 
      } 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    System.out.print(Arrays.toString(playerOne)); 
} 

我得到一個NoSuchElementException異常錯誤,而且無法打印陣列

+1

從未使用'下一個()'它讀取換行符作爲一個單獨的字符。而是使用'nextLine()'和'split()'來創建一個字符串數組 – SkrewEverything

+0

@skrer實際上使用next()更好 –

+0

@BasilBattikhi我可能是錯的,但我會很感激一個解釋。 – SkrewEverything

回答

1

而是採用nextLine使用.next直接 。接下來將獲得下一個值,而不管下一個值線

try { 
     Scanner sc = new Scanner(new File("test.txt")); 
     while (sc.hasNext()) { 
      for (int i = 0; i < 6; i++) { 
       for (int j = 0; j < 3; j++) { 
        String nextValue= sc.next().trim(); 
         playerOne[i][j] = nextValue; 
         System.out.println(i+ " " +j+ " "+ nextValue); 

       } 
      } 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    System.out.print(Arrays.toString(playerOne)); 
}