2016-03-05 117 views
0

我对Java很新,但我觉得这是一件容易的事。这个数组列表有两个元素...名字和分数。我想写一个方法来打印列表中所有名字的列表,而不是分数。我知道我笑ArrayList包含两个元素,如何只返回String元素?

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

回答

0
public void printAllNames() {//this is the method. 
    for (Classroom s : scores){ 
    System.out.println(s.returnName()); 
    } 
} 

你应该在你的问题进行precice,您的列表中不包含2个元素 - 名称和分数 - 但包含名称和分数的多个Classroom对象。使用Java 8流

备选答案:

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

太谢谢你了。我完全明白! – feelingstoned

+0

不客气 – MartinS

相关问题