2017-10-08 30 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)); 
}