简体   繁体   English

在对象类型的二维数组中插入字符串值

[英]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.我正在尝试从文件中读取内容并将其放入对象类型 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();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 . Scanner#next()默认返回一个String但您试图将其存储为Box类型的数组。

Instead of doing that you should create a Box object an store it that way.而不是这样做,您应该创建一个 Box 对象并以这种方式存储它。 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). bx[row][col]意味着您将为 5,7 分配一个值(在本例中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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