2015-10-21 83 views
1

我試圖從文本文件中讀取點和X的網格,並將它們添加到數組並將它們打印爲一個大網格。出於某種原因,它以數據塊的形式打印數組的部分,在控制檯的這些數據塊之間有大的空間。如果我使用一個toString它打印內存位置,所以我不知道什麼怎麼回事...陣列打印大空間?

代碼:

import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.util.Arrays; 
import java.util.Scanner; 

public class Project4 { 

    public static void main(String[] args) throws IOException { 
     Scanner input = new Scanner(System.in); // Created a scanner 
     System.out.println("Enter the file name you would like to use"); 
     File file = new File(input.nextLine()); // Takes file name to find file 
     Scanner inputFromFile = new Scanner(file); 
     String line = inputFromFile.nextLine(); 
     FileInputStream fileInput = new FileInputStream(file); // reads file 
     int r; 
     while ((r = fileInput.read()) != -1) { // goes through each character in 
               // file, char by char 
      char c = (char) r; 
      for (int i = 0; i <= 4; i++) { 
       for (int y = 0; y <= 3; y++) { 
        GameOfLife.grid[i][y] = c; 
        for (int j = 0; j < GameOfLife.grid.length; j++) 
         System.out.println(GameOfLife.grid[j]); 
       } 
      } 
     } 

    } 
} 

GameOfLife:

import java.util.Arrays; 

public class GameOfLife { 

static final int m = 25; // number of rows 
static final int n = 75; // number of columns 
static char[][] grid = new char [m][n]; // Creates an empty (no dots or X's)grid of rows and columns. 


} 
+0

哪裏是GameOfLife的代碼 –

+0

對不起,我的壞。現在添加它 –

+0

使用'system.out.print'而不是'system.out.println' – SacJn

回答

1

嘗試打印陣列的內容while循環之外。你正在做的是打印每個字符添加到你的網格的所有內容

0

要打印每個角色之後的網格。

你需要的東西,如:

// Walk the whole grid. 
    for (int i = 0; i <= 4; i++) { 
     for (int y = 0; y <= 3; y++) { 
      // Read a character from the file. 
      int r = fileInput.read(); 
      if (r != -1) { 
       GameOfLife.grid[i][y] = (char) r; 
      } else { 
       // End of file before grid filled!!! TODO! Deal with this. 
      } 
     } 
    } 
    // Print out the results. 
    for (int j = 0; j < GameOfLife.grid.length; j++) { 
     System.out.println(GameOfLife.grid[j]); 
    }