【问题标题】:How to construct an array in a class in java and call it?如何在java中的类中构造一个数组并调用它?
【发布时间】:2015-10-27 02:34:26
【问题描述】:

我是一名初级 Java 程序员,在类中构造一个数组然后调用它并使用它时遇到了一些问题。所以我有一个有 2 个类的程序。第一个称为 MyDate,旨在声明实例变量、构造函数,然后声明为 toString() 方法。从那里我正在创建另一个名为 DateArray 的类,它创建一个名为 dateArr 的 MyDate 数组。

package date_array;

class MyDate {
    public int day;
    public String month;
    public int year;

    public MyDate(String month, int day, int year)
    {
        this.day = day;
        this.month = month;
        this.year = year;
    }

    public String toString()
    {
        return (month + " " + day + " " + year);
    }

    public class DateArray {
        MyDate[] dateArr = new MyDate[4];
        dateArr[0] = new MyDate("May", 16,1984);
        dateArr[1] = new MyDate("May", 16,1984);
        dateArr[2] = new MyDate("May", 16,1984);
        dateArr[3] = new MyDate("May", 16,1984);
    }

    public static void main(String[] args) {
        MyDate[] dateArr = new MyDate[4];
        dateArr.toString();
    }
}

这是我到目前为止的代码。我真的很努力在 DateArray 类中构建数组而没有出现异常错误等。我曾尝试将事情转移到主要内容并使用不同的措辞,但后来查看了我的笔记和许多谷歌搜索,我仍然完全卡住了。我真正需要帮助的是在 DateArray 类中创建我的数组,然后将所需的数组打印到控制台。任何帮助都会很棒。非常感谢!

【问题讨论】:

  • 您似乎对类的用途感到困惑。请记住,您不能只在类的主体内执行代码。在DateArray 中分配给dateArr 是非法的。此外,如果你的类只包含一个数组,那么它完全是多余的。
  • 另外,在数组上调用 toString 只会得到数组的地址。使用Arrays.toString()

标签: java arrays class


【解决方案1】:

首先,您最好将创建每个数组实例放在 DataArray 类的构造方法中。 toString() 方法不会打印出任何内容,相反,它只会为您返回字符串值。所以你应该在 main 方法上打印出消息。请以以下代码为例:

public class DateArray {

   MyDate[] dateArr = new MyDate[4];
   public DateArray(){
        dateArr[0] = new MyDate("May", 16,1984);
        dateArr[1] = new MyDate("May", 16,1984);
        dateArr[2] = new MyDate("May", 16,1984);
        dateArr[3] = new MyDate("May", 16,1984);
   }
   public String toString()
   {
       String str = "";
       for(int i=0; i<dateArr.length;i++){
            str = str+ dateArry[i].toString();
        }
       return str;
   }
   public static void main(String[] args) {

          DateArray array = new DateArray();
          System.out.println(array);

    }

}

【讨论】:

  • 您应该解释您对 OP 的代码所做的更改,而不是仅仅张贴一堵未注释的代码。
【解决方案2】:
package date_array;

import java.utils.Arrays;

class MyDate {
    public int day;
    public String month;
    public int year;

    public MyDate(String month, int day, int year)
    {
        this.day = day;
        this.month = month;
        this.year = year;
    }

    public String toString()
    {
        return (month + " " + day + " " + year);
    }

    /*public class DateArray {
        MyDate[] dateArr = new MyDate[4];
        dateArr[0] = new MyDate("May", 16,1984);
        dateArr[1] = new MyDate("May", 16,1984);
        dateArr[2] = new MyDate("May", 16,1984);
        dateArr[3] = new MyDate("May", 16,1984);
    }*/
    // The above code does nothing

    public static void main(String[] args) {
        MyDate[] dateArr = new MyDate[4];
        dateArr[0] = new MyDate("May", 16,1984); // add these to populate the array, otherwise it will be an array of nulls
        dateArr[1] = new MyDate("May", 16,1984);
        dateArr[2] = new MyDate("May", 16,1984);
        dateArr[3] = new MyDate("May", 16,1984);
        // dateArr.toString(); This does nothing, but would have also only given you the address of the array anyways and nothing useful
        System.out.println(Arrays.toString(dateArr)); // print to the console using the Arrays.toString utility. This is a convenience method that iterates through the array and calls toString on each element and also gracefully handles null
    }
}

如果你必须有 DateArray 类:

package date_array;

import java.utils.Arrays; // import the arrays library

class MyDate {
    public int day;
    public String month;
    public int year;

    public MyDate(String month, int day, int year)
    {
        this.day = day;
        this.month = month;
        this.year = year;
    }

    public String toString()
    {
        return (month + " " + day + " " + year);
    }

    public class DateArray {
        private MyDate[] dateArr = new MyDate[4]; // package scoped member array, should probably be private

        DateArray() { // move array initialization into constructor so that it is populated when the class is instantiated
            dateArr[0] = new MyDate("May", 16,1984);
            dateArr[1] = new MyDate("May", 16,1984);
            dateArr[2] = new MyDate("May", 16,1984);
            dateArr[3] = new MyDate("May", 16,1984);
        }

        public String toString() { // override the toString method so that when you just pass it to print it knows how to turn it into a string, otherwise it will just print the address of the object.
            return Arrays.toString(dateArr);
        }
    }

    public static void main(String[] args) {
        DateArray dateArr = new DateArray();
        System.out.println(dateArr); // You can call dateArr.toString, but this is done by the println method internally, so not necessary
    }
}

此外,如果不允许您使用 Arrays.toString 方法,那么您必须自己实现一个 null 安全实现,如下所示:

public String toString() {
    String toReturn = "[ "; // initialize the string that you will append to
    for (int i = 0; i < dateArr.length; ++i) { // iterate through the array with i being the index
        if (i != 0) // if it isn't the first one
            toReturn += ", "; // insert a separator
        if (dateArr[i] == null)
            toReturn += "NULL"; // append the word null, because the array index is null
        else
            toReturn += dateArr[i]; // append the index's toString
    }
    toReturn += " ]"; // close off the array visualization
    return toReturn;
}

注意: 上面的代码应该使用 StringBuilder,但为 OP 进行了简化。以这种方式附加字符串(使用 +=)将“污染”Java 字符串池。虽然优化器会尝试自动纠正此错误,但并不能保证。

【讨论】:

  • 您应该解释您对代码所做的更改,OP 显然无法理解您在这里所做的事情。帮助他们,而不是为他们做。
  • @LukePark 更改已在 cmets 中进行了解释,但会添加更多内容。
猜你喜欢
  • 2010-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2023-04-03
  • 2020-11-07
相关资源
最近更新 更多