java - 如何将对象数组打印到屏幕上?

标签 java oop

我想将日期数组 (myDates) 中的每个日期对象打印到屏幕上。 日期类具有月、日和年的值。

private static void printDates(Date[] myDates) throws IOException {
    @SuppressWarnings("resource")
    Scanner input = new Scanner(System.in);
    if(myDates.length == 0) {
        System.out.println("There are no dates to print.\n");
}
    else {
        System.out.println("Print the dates to the screen or to a file?");
        System.out.println("  1. Print to screen.");
        System.out.println("  2. Print to a new file.");
        System.out.print("Choice: ");
        int option = input.nextInt();
        System.out.println("");
        if(option == 1) {
            for(int i = 0; i < myDates.length; i++) { //Is this necessary?
                //Don't know how to print array of objects with toString method in date class.
            }

我认为这与日期类的 get 和 set 方法有关,但不太确定如何正确执行这些操作。

public String getDate() {
    return "" + month.getMonth() + " " + day.getDay() + " " + year.getYear();
}

public void setDate(Date date) {
    //maybe make a date string then this.date = date; ???
}

或者也许您会使用日期类的 toString 方法?这可能不正确。

public String toString(e) {
    return getMonthWord(day.toString()) + " " + month.toString() + " " + year.getYear();
}

最佳答案

I want to print each date object in the array of dates (myDates) to the screen.

首先,对于 toString() 方法,您不需要传入参数,因为您已声明您创建的 toString() 方法确实是不正确。

更改此:

public String toString(e) {
    return getMonthWord(day.toString()) + " " + month.toString() + " " + year.getYear();
}

对此:

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

考虑到数组中的每个日期都有一个toString(),您可以简单地执行以下操作:

if(option == 1) {
    Arrays.stream(myDates).forEach(System.out::println);
}

或使用典型的 foreach 循环:

if(option == 1) {
     for(Date d : myDates) System.out.println(d);
}

基本上,每当 System.out.println 调用数组中的任何 Date 对象时,都会发生 toString() 方法会针对特定的 Date 对象自动调用,您无需说 d.toString()

关于java - 如何将对象数组打印到屏幕上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43431753/

相关文章:

java - JAVA8 中如何通过 lambda 表达式将 Map 转换为 SortedMap?

java - Kotlin Arraylist 与 Java Arraylist 的类型不匹配

java - 运行时的通用类​​类型参数详细信息

java - 抽象方法与无实例方法?

c++ - 包含另一个对象的指针 vector 的对象

PHP 数据映射器 setter / getter

java.lang.IllegalArgumentException : Cannot instantiate interface org. springframework.context.ApplicationContextInitializer

java - Appium-如何使用Java从iOS设备读取日志

c++ - 如何将一个类的部分公共(public)接口(interface)限制为只有一个类?

python - Python 中的类、方法和多态性