Java 我想读取一个文本文件,并以8*8数组的形式显示该文件的内容
示例:Java 我想读取一个文本文件,并以8*8数组的形式显示该文件的内容,java,file,Java,File,示例: 假设我的文件是: 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.ou
假设我的文件是:
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();
}
}
}
我将以以下形式获得输出:12345678
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]);
}
}
publicstaticvoidmain(字符串[]args)引发IOException
{
BufferedReader file=新的BufferedReader(新文件读取器(“文件路径”);
扫描仪sc=新扫描仪(文件);
int k=sc.nextInt();
if(iRow
intirow=0//柜台
int-iColumn=0//计数器列
int[]myArray=新的int[行][列];
... 虽然
int k=sc.nextInt;
if(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();
//{...}
%是模运算符,它返回整个除法后的余数
例如
您的“我想显示为”与“8x8数组形式”不匹配,它更像是一个2x4。。。哪个更适合8个输入元素。那么,“8x8数组形式”是什么意思呢?我只是用它作为一个例子来描述我真正想要实现的东西。无论文件内容是什么,我都希望以网格形式读取和显示它。我尝试过这样做,但当我想要打印2d数组时,我遇到了ArrayIndexOutOfBounds异常。你能帮我吗?在
while
之后,你必须for(inti=0;i
构建成功,但它不显示任何输出@乌佛
//{...}
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