当前位置: 动力学知识库 > 问答 > 编程问答 >

file to array in java. what is wrong with this code?

问题描述:

I dont understand what is wrong with this code. I want to read txt file

11,10

2,20

into array[][] in java.

My code is

import java.util.Arrays;

class ArrayMatrix{

public static void main (String[] args) {

int rows = 2;

int cols = 2;

FileInput in = new FileInput("test.txt");

int[][] circle = new int[rows][cols];

int i = 0;

int j = 0;

String [] line;

for(i = 0; i<rows; i++) {

line = in.readString().split(",");

for(j = 0; j<cols; j++) {

circle[i][j] = Integer.parseInt(line[j]);

System.out.println(circle[i][j]);

}

}

}

}

The output is

11

10

2

20

Could you please help me understand why please?

I want the output

11 10

2 20

网友答案:

You're output is like this since you're just using the System.out.println(circle[i][j]) command in the middle which only prints to a single line. Using the System.out.print command should help you print correctly. As show in the following altered code sample

import java.util.Arrays;
class ArrayMatrix{
   public static void main (String[] args) {
   int rows = 2; 
   int cols = 2;
   FileInput in = new FileInput("test.txt");
   int[][] circle = new int[rows][cols]; 
   int i = 0; 
   int j = 0; 
   String [] line;
   for(i = 0; i<rows; i++) { 
       line = in.readString().split(",");
       for(j = 0; j<cols; j++) { 
           circle[i][j] = Integer.parseInt(line[j]);
           System.out.print(circle[i][j] + " ");
       }
       System.out.println();
    }
}
}
网友答案:

Why are you trying to split the string using comas, when you don't have comas separating values on each line?

line = in.readString().split(",");  //this is expecting coma separated values on each line

Also System.out.println() puts a new line at the end. So thats why they end on separate lines. Use System.out.print(circle[i][j]) instead.

网友答案:

When you use println(), each element is written on a new line. Try:

   for(j = 0; j<cols; j++) { 
       circle[i][j] = Integer.parseInt(line[j]);
       System.out.print(circle[i][j] + " ");
   }
   System.out.println();
分享给朋友:
您可能感兴趣的文章:
随机阅读: