简体   繁体   中英

Inserting String values in a 2D array of an Object type

I am trying to read contents from a file and put it into a 2D array of Object type Box. Its giving me a type error. Can somebody please help me?

import java.io.*;
import java.util.Scanner;

public class Gameboard
{
  private Box[][] bx;

  public Gameboard (String fileNm)
   {
    try {

        BufferedReader input = new BufferedReader(fileNm);
        Scanner lineReader = new Scanner(input.readLine());

        while (lineReader.next() != null)
        {
            bx = new Box[row][col];
            for(int i = 0; i < row; i++)
               for(int j = 0; j < col; j++)
               {
                    bx[row][col] = lineReader.next(); // the error is here
               }
        }

}

Yeap the error is expected. In bx[row][col] = lineReader.next(); you attempt to read a value. Scanner#next() by default returns a String but you're attempting to store it an array of type Box .

Instead of doing that you should create a Box object an store it that way. Also, you know that you're not traversing all the rows and cols. bx[row][col] would mean that you'll be assigning a value to 5,7 (in this example).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM