我想读取一个文本文件并以8 * 8数组形式

时间:2018-04-20 09:16:56

标签: java file

例:
假设我的文件是:

1  
2  
3  
4  
5  
6  
7  
8  

我想将其显示为:

1 2 3 4  
5 6 7 8  

我能够从文件中读取并能够显示文件内容 我使用这种方法从文件和显示中读取,但我无法找到一种方法将它带入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]);
 }
  }

2 个答案:

答案 0 :(得分:0)

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++;
  }


}

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

答案 1 :(得分:0)

只需加入循环

//{...}
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