【问题标题】:An ArrayList contains two elements, how to return only the String element?一个 ArrayList 包含两个元素,如何只返回 String 元素?
【发布时间】:2016-06-18 22:34:38
【问题描述】:

我对 Java 还很陌生,但我觉得这是一项简单的任务。这个数组列表有两个元素……名字和分数。我想编写一个方法来打印列表中所有名称的列表,而不是分数。我知道我之前已经这样做了,我只是不记得如何大声笑

import java.util.ArrayList;
/**
 * Print test scrose and student names as well as he average for the class.
 */
public class TestScores {
  private ArrayList<Classroom> scores;
  public int studentScores;

  /**
   * Create a new ArrayList of scores and add some scores
   */
  public TestScores() {
    scores = new ArrayList<Classroom>();
  }

  /**
   * Add a new student and a new score.
   */
  public void add (String name, int score) {
    scores.add(new Classroom(name, score));
    if(score > 100){
      System.out.println("The score cannot be more than 100");
    }    
  }

  /**
   * Return all the student names.
   */
  public void printAllNames() {//this is the method.
    for (Classroom s : scores){
      System.out.println(scores.get(name));
    }
  }
}

和课堂:

import java.util.ArrayList;
/**
 * This class creates the names and scores of the students
 */
public class Classroom {
  public int score;
  public String name;

  /**
   * Constructor for the Class that adds a name and a score.
   */
  public Classroom(String aName, int aScore) {
    score = aScore;
    name = aName;
  }

  /**
   * Return the name of the students
   */
  public String returnName() {
    return name;
  }

  /**
   * Return he scores
   */
  public int returnScore() {
    return score;
  }
}

【问题讨论】:

    标签: java arraylist return


    【解决方案1】:
    public void printAllNames() {//this is the method.
      for (Classroom s : scores){
        System.out.println(s.returnName());
      }
    }
    

    您的问题应该是精确的,您的列表不包含 2 个元素 - 名称和分数 - 而是包含名称和分数的多个 Classroom 对象。

    使用 Java 8 流的替代答案:

    scores.stream().map(c -> c.returnName()).forEach(System.out::println);
    

    【讨论】:

    • 非常感谢。我完全明白了!
    猜你喜欢
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多