Error on filling my 2D array in java from a text file

55 views Asked by At

I am attempting to create the Game of Life, but have hit a hard point early on. :(

I have a text file with "o" and "*" as the starting grid/matrix and my constructor has to read that file and fill a 2D array with it.

Problem is that I have an error where it says "sc.nextLine();", i'm not too sure what I am missing to fill in array.

import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;

   public class LifeGrid {

   int x, y;

   public LifeGrid(int newy, int newx, String filename) {
   x = newx;
   y = newy;
   File file = new File(filename);
   Scanner sc = new Scanner(file);
   int[][] board = new int[y][x];
   while (sc.hasNext())
   {
      for (int i = 0; i < y; i++)
      {
        for (int j = 0; j < x; j++)
        {
          board[i][j] = sc.nextLine(); <- error here
        }
      }
   }
}
1

There are 1 answers

2
Wojciech Tomczyk On

The simplest solution:

  for (int i = 0; i < y; i++)
  {
    String line = sc.nextLine();
    for (int j = 0; j < x; j++)
    {
      board[i][j] =  line.charAt(j)=='*'?1:0;
    }
  }