Reputation: 97
I have file MatrixToCsv.csv like this:
67,85,20,87,78,46,66;
33,66,88,24,90,28,19;
76,22,46,33,10,16,73;
16,79,28,98,67,49,62;
85,75,12,18,92,58,80;
59,89,16,10,52,67,35;
54,66,62,53,39,91,37;
And i want to save it to an array but only the integers, so I have written this:
public static void main(String[] args) throws IOException {
Scanner input = new Scanner (new File("MatrixToCsv.csv"));
int rows = 7;
int columns = 7;
int[][] array = new int[rows][columns];
input.useDelimiter(Pattern.compile(",|;|(\\n)"));
for(int i = 0; i < rows; ++i)
{
for(int j = 0; j < columns; ++j)
{
if(input.hasNextInt())
{
array[i][j] = input.nextInt();
}
}
}
for(int i = 0; i < rows; i++) {
for (int j = 0; j < array.length; j++) {
System.out.print(array[i][j]+ " ");
}
System.out.println();
}
input.close();
}
And the output is:
67 85 20 87 78 46 66
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
And I am wondering why it reads only one line from text. Thanks. Q.
Upvotes: 0
Views: 64
Reputation: 22243
input.useDelimiter(Pattern.compile(",|;|(\\n)"));
Here, you are basically saying that the delimiter can be a single comma OR a single semicolon OR a single newline character.
At the end of each line you have both semicolon and newline, which is not what you set your scanner to use as delimiter. Use [,;\\n]+
instead, which means "one between ,
, ;
and \n
repeated at least one time". This way you'll match ;\n
too.
input.useDelimiter(Pattern.compile("[,;\\n]+"));
Upvotes: 3