Reputation: 21
What i'm trying to do is put a text file in a matrix array then display all the numbers. I've got it to display the numbers but they are all zeros.
Here is my code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class is12177903
{
public static int[][] read_input(String filename) throws FileNotFoundException
{
int matrix [][] = null;
BufferedReader buffer = new BufferedReader(new FileReader(filename));
String line;
int row = 0;
int size = 0;
try {
while ((line = buffer.readLine()) != null)
{
String[] vals = line.trim().split("\\s+");
if (matrix == null)
{
size = vals.length;
matrix = new int[size][size];
}
for (int col = 0; col < size; col++)
{
matrix[row][col] = Integer.parseInt(vals[col]); //this is line 31
}
row++;
}
} catch (NumberFormatException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return matrix;
}
public static void printMatrix(int[][] matrix)
{
String str = "";
int size = matrix.length;
if (matrix != null) {
for (int row = 0; row < size; row++)
{
str += " ";
for (int col = 0; col < size; col++)
{
str += String.format("%2d", matrix[row][col]);
if (col < size - 1)
{
str += "";
}
}
if (row < size - 1)
{
str += "\n";
}
}
}
System.out.println(str);
}
public static void main(String[] args)
{
int[][] matrix = null;
try {
matrix = read_input("AI2015.txt"); // this is line 83
} catch (Exception e) {
e.printStackTrace();
}
printMatrix(matrix);
}
}
The text file i'm reading from is just 26x26 with integers that are either 1 or 0.
I have some errors that show up every time i run it and I'm not sure what they mean: java.lang.NumberFormatException: For input string: "0"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at is12177903.read_input(is12177903.java:31)
at is12177903.main(is12177903.java:83)
Upvotes: 2
Views: 88
Reputation: 6541
As @Seelenvirtuose has stated, it is an issue with UTF-8 encoding.
However, I believe you do not need to edit your text file, just change your BufferedReader
as so:
BufferedReader buffer = new BufferedReader(new InputStreamReader(
new FileInputStream(filename), StandardCharsets.UTF_8));
Upvotes: 1
Reputation: 20618
Your file is saved in UTF-8 encoding with a byte order mark (BOM)!
The UTF-8 byte order mark consists of exactly three bytes: 0xEF 0xBB 0xBF
. You are instantiating a FileReader
, which will use the platform default encoding. In many cases this is ISO-8859-1. The characters you see, are the ISO-8859-1 characters for those three bytes. Obviously they are invalid input.
There are two solutions:
Remove the BOM. UTF-8 BOMs are really uncummon, and there are many programs that cannot deal with it. So the best is, to not have it.
Set the encoding to UTF-8 using an InputStream
as in @budi's answer.
Upvotes: 2