while (input.next()!=null)
This will consume something from the scanner input stream. Try using insteadwhile (input.hasNextInt())
Depending on how reliable your code is, you should also check inside the for loop that something is readable.
Scanner input = new Scanner (new File("src/array.txt"));
int rows = 0;
int columns = 0;
while(input.hasNextLine())
{
++rows;
Scanner colReader = new Scanner(input.nextLine());
while(colReader.hasNextInt())
{
++columns;
}
}
int[][] a = new int[rows][columns];
input.close();
input = new Scanner(new File("src/array.txt"));
for(int i = 0; i < rows; ++i)
{
for(int j = 0; j < columns; ++j)
{
if(input.hasNextInt())
{
a[i][j] = input.nextInt();
}
}
}
Alternative using ArrayLists (without prior reading):
ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>();
Scanner input = new Scanner(new File("src/array.txt"));
while(input.hasNextLine())
{
Scanner colReader = new Scanner(input.nextLine());
ArrayList col = new ArrayList();
while(colReader.hasNextInt())
{
col.add(colReader.nextInt());
}
a.add(col);
}
source
share