我想读取一个文本文件并以 8*8 数组形式显示文件的内容



示例:
假设我的文件是:

1  
2  
3  
4  
5  
6  
7  
8  

我想将其显示为:

1 2 3 4  
5 6 7 8  

我已经能够从文件中读取并能够显示文件内容。
Iv'e 使用这种方法从文件读取和显示,但我无法找到一种将其转换为 8*8 数组形式的方法。

public class FileRead  
{
public static void printRow(int[] row) 
{
    for (int k : row) 
    {
        System.out.print(k);
        System.out.print("t");
    }
    System.out.println();
  }

  public static void main(String[] args)
{
File file = new File("filepath");
int i,j;
int row = 8;
int column = 8;
int [][] myArray = new int [row][column];
try 
{
   Scanner sc = new Scanner(file);
    while (sc.hasNextLine()) 
    {
    int k = sc.nextInt();
        System.out.print(k);
        System.out.print("t");
        }
    System.out.println();

   /*for(int[] row : myArray) 
    {
        printRow(row);
    }*/
    sc.close();
} 
catch (FileNotFoundException e) {
    e.printStackTrace();
}
}
}  

我以这种形式获得输出:
1 2 3 4 5 6 7 8...

public static void main(String[] args) throws IOException 
{
 BufferedReader file = new BufferedReader(new FileReader("filepath"));
 Scanner sc = new Scanner(file);
  int k = sc.nextInt();
  if(iRow < myArray.length && iColumn < myArray[iRow].length) 
  {
    myArray[iRow][iColumn] = k;
iColumn++;
if(iColumn == myArray[iRow].length)  
{
 iColumn = 0;
 iRow++;
}
 }
  System.out.print(myArray[iRow][iColumn]);
 }
  }
int iRow = 0; //Counter row
int iColumn = 0;  //Counter column
int [][] myArray = new int [row][column];
... while ...
int k = sc.nextInt;
if(iRow < myArray.length && iColumn < myArray[iRow].length) // the counter cant be greater than the array row; same with column
{
  myArray[iRow][iColumn] = k;
  iColumn++;
  if(iColumn == myArray[iRow].length)  //if you access the last column; go to the next row
  {
     iColumn = 0;
     iRow++;
  }

}

此代码将填充您的数组 [][]。

只需添加到您的循环中

即可
//{...}
int newLineAfter = 4;
for (int k: row) {
 System.out.print(k);
 System.out.print("t");
 //when k will be 4*n- 4, 8, 12, 16... 
 if (k % newLineAfter == 0) {
  System.out.println();
 }
}
System.out.println();
//{...}

% 是模运算符,它返回整个除法后的余数例如。

1 % 2 = 2
2 % 2 = 0 
3 % 2 = 1 
4 % 2 = 0
8 % 4 = 0 
9 % 4 = 1 
10 % 4 = 2

最新更新