如何在java中的类中构造一个数组并调用它?

时间:2015-10-27 02:34:27

标签: java arrays class

我是一个初学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类中创建我的数组,然后将所需的数组打印到控制台。任何帮助都会很棒。非常感谢!

2 个答案:

答案 0 :(得分:0)

首先,您最好将每个数组实例的创建放在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);

    }

}

答案 1 :(得分:0)

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方法,那么您必须自己实现一个空安全实现,如下所示:

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进行了简化。以这种方式附加字符串(使用+ =)将“polute”&#39; Java字符串池。虽然优化器会尝试自动纠正这个错误,但不能保证。