【问题标题】:Instantiate 2D Array of objects using multiple classes使用多个类实例化 2D 对象数组
【发布时间】:2016-05-24 12:23:44
【问题描述】:

我的作业碰壁了。

我创建了一个二维对象数组,我需要使用各种类对其进行实例化。

还有一大堆其他要求,但我(目前)主要担心的是我无法弄清楚为什么我得到一个 ' c ' 而不是 ' 的数组。 '

这是我的一段代码,有 Driver 类、Item 类、Dot 类和 Array 类。

任何帮助将不胜感激。

    public class Driver
    {

      public static void main(String[] args) 
      {
      Driver a = new Array();
      ((Array) a).runArray();
      }
   }

    public abstract class Item extends Driver
    {

     private char component;

     public Item (char c)
     {
       component = 'c';
     }


    public char display()
   {
     return component;
   }


  //create a new array of objects.
  Item[][] array = new Item [10][10];

  }

 public class Dot extends Item
 {

   public Dot () 
   {
     super('.');
   }

 import java.util.*;

 public class Array extends Item
 {

   Array() 
  {
    super(c);
  }

  Random randGen = new Random();
  private int CoordX = randGen.nextInt(3);
  private int CoordY = randGen.nextInt(3);


    public void runArray()
    {
        setArray();
        displayArray(); 
    }


    private void setArray()
    {
        for (int row = 0; row < array.length; row++) 
            for (int col = 0; col < array[row].length; col++)
                    array[row][col] = new Dot();
    }


    private void displayArray()
    {
        for (int row = 0; row < array.length; row++){ 
            for (int col = 0; col < array[row].length; col++){
                System.out.print(array [row][col].display()+"\t"); 
            }
            System.out.println("\n");
        }
    }

【问题讨论】:

    标签: java arrays oop object


    【解决方案1】:

    因为无论你如何调用Item 的构造函数,它始终是char c

    public Item (char c)
         {
           component = 'c';
         }
    

    改成

    public Item (char c)
         {
           component = c;
         }
    

    【讨论】:

    • @user4824195 不要忘记将此答案标记为正确。
    猜你喜欢
    • 2014-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多