2016-03-05 1 views
0

Я довольно новичок в Java, но чувствую, что это простая задача. У этого arraylist есть два элемента ... имена и оценки. Я хочу написать метод, который печатает список всех имен в списке, а не оценки. Я знаю, что я сделал это раньше, я просто не могу вспомнить, как лол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

Смежные вопросы