簡體   English   中英

為什么我的掃描文件並打印出結果的方法比上次打印出 1 個空格?

[英]Why does my method that scans a file and prints out the result print 1 space further than the last time?

我目前正在編寫一段相當長的代碼來重新創建康威的生命游戲,並且剛剛意識到當我運行我的代碼時,我用來掃描文件並將自身打印為矩陣的方法無法按預期工作. 我試過弄亂它,但無濟於事。

public static String[][] originalBoardCreation() {
        Scanner sc= MyUtils.readFile(inpFileName);
        
        width = sc.nextInt();
        height = sc.nextInt();  
        sc.nextLine();
        
        String[][] board = new String[width][height];
        String[] line = new String[board.length];
        
        while (sc.hasNext()) {
            for (int i = 0; i < board.length; i++) {
                line[i] = sc.nextLine().trim();
                
                for (int j = 0; j < line.length; j++) {
                    board[i][j] = line[j];
                }
            }
        } 
        
        return board;
    }

當我用System.out.println(Arrays.deepToString(originalBoardCreation()));調用它時 ,我得到

[[.xxxxxxxx., null, null, null, null, null, null, null, null, null], [.xxxxxxxx., x.x.x.x.x., null, null, null, null, null, null, null, null], [.xxxxxxxx., x.x.x.x.x., .x.x.x.x.., null, null, null, null, null, null, null], [.xxxxxxxx., x.x.x.x.x., .x.x.x.x.., xxxxxxx..., null, null, null, null, null, null], [.xxxxxxxx., x.x.x.x.x., .x.x.x.x.., xxxxxxx..., .........., null, null, null, null, null], [.xxxxxxxx., x.x.x.x.x., .x.x.x.x.., xxxxxxx..., .........., .........., null, null, null, null], [.xxxxxxxx., x.x.x.x.x., .x.x.x.x.., xxxxxxx..., .........., .........., .........., null, null, null], [.xxxxxxxx., x.x.x.x.x., .x.x.x.x.., xxxxxxx..., .........., .........., .........., ....xxx..., null, null], [.xxxxxxxx., x.x.x.x.x., .x.x.x.x.., xxxxxxx..., .........., .........., .........., ....xxx..., .........., null], [.xxxxxxxx., x.x.x.x.x., .x.x.x.x.., xxxxxxx..., .........., .........., .........., ....xxx..., .........., ..........]]

我試圖得到類似[[., x, x, x, x, x, x, x, x, .], ... etc的東西,但我不知道為什么會這樣,所以它如果我能在我的邏輯中得到一個簡短的解釋或錯誤,那就太好了,謝謝!

我相信問題是由於您從文件中讀取一行文本並期望它被神奇地分割成一個字符串數組。

public static String[][] originalBoardCreation()
{
  Scanner sc= MyUtils.readFile(inpFileName);

  width = sc.nextInt();
  height = sc.nextInt();  
  sc.nextLine();

  String[][] board = new String[width][height];

  while ( sc.hasNext() )
  {
    for ( int i = 0; i < board.length; i++ )
    {
      String line = sc.nextLine().trim();  // read the text line in
      char tiles[] = line.toCharArray();    // now split the line into an array

      for ( int j = 0; j < tiles.length; j++ )
      {
        board[i][j] = String.valueOf(tiles[j]);  // Now assign the elements to the current row on your board
      }
    }
  } 
  return board;
}

我還沒有測試過這個,但是這樣的東西應該可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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