1 Attachment(s)
New person Just trying to read a file of ints
Hello,
I am trying to read a simple .txt file of ints into a 2D array. However, the scanner object seems to skip the first few ints. The "scanner.hasNext()" seems to advance the scanner. Please let me know what I am doing wrong. I attached the file "input.txt" Thanks
Code :
public int[][] getMatrix(String fileName)
{
int totalrows = 0;
int totalcols= 0;
int[][] matrix = null;
File file = null;
Scanner scanner = null;
int rowIndex = 0;
int colIndex = 0;
try
{
scanner =new Scanner(new File("input.txt"));
}
catch (FileNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
System.out.println ("File not found!");
// Stop program if no file found
System.exit (0);
}
while (scanner.hasNext())
{
if (scanner.hasNextInt())
totalrows = scanner.nextInt();
if (scanner.hasNextInt())
totalcols = scanner.nextInt();
else
scanner.next();
}
matrix = new int[totalrows][totalcols];
while (true)
{
if (!scanner.hasNextInt() || !(scanner.next() == "\r") || !(scanner.next() == " "))
break;
matrix[rowIndex][colIndex] = scanner.nextInt();
rowIndex++;
if (scanner.next() == "\r")
{
rowIndex = 0;
colIndex++;
}
}
return matrix;
}
Re: New person Just trying to read a file of ints
The hasNext method doesn't advance the read point. However, in the point where you're reading in data, you use the next() method, which will advance the read point.
A suggestion would be to simply read in the number of integers that should be in that file.
Code :
for (int i = 0; i < totalrows; i++)
{
for (int j = 0; j < totalcols; j++)
{
matrix[i][j] = scanner.nextInt();
}
}