printing data of specific element from array in ja

2019-09-22 06:43发布

This question already has an answer here:

I have an array of a class type which stores videos (not real ones just objects). Each video has a title and an author. The videos have their data set using set methods like these:

 public class Clip {

 private String title;
 private String author;

     public void setTitle (String s1) {

        title = s1;

    }

     public void setAuthor (String s2) {

        title = s2;

    }

I then have a different class which creates the array and uses these set methods to enter data. The program then asks the user to select an element from the array, for example the user selects element [3]. Now the program must print the title and author of that element(video).

This is the part I am not sure how to do? Can I please have some help?

8条回答
做自己的国王
2楼-- · 2019-09-22 07:07

Basically you have two options:

  1. Create getters in the Video-Class, e.g.public String getTitle() { return title; }
  2. Override the toString function to output the value you want, e.g.

    @Override public String toString() { return "Author: " + author + ", Title: " + title"; }

查看更多
乱世女痞
3楼-- · 2019-09-22 07:07

Override toString method of Clip. Every invocation of print* (e.g. println) method would call toString method of an object.

    @Override
    public String toString() {
        return "[Title: " + this.title +", Author: " + this.author + "]";
    }

Example after overriding method:

    Clip clip1 = new Clip();
    Clip clip2 = new Clip();
    Clip[] clipArray = {clip1, clip2};

    for (Clip clip : clipArray) {
        System.out.println(clip);
    }
查看更多
登录 后发表回答