ArrayList包含两个元素,如何只返回String元素?

时间:2016-03-05 01:12:34

标签: java arraylist return

我对Java很陌生,但我觉得这是一件容易的事。这个arraylist有两个元素......名字和分数。我想编写一个方法来打印列表中所有名称的列表,而不是分数。我知道我已经做到了这一点,然而我才能记住lol

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;
  }
}

1 个答案:

答案 0 :(得分:0)

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);