【发布时间】:2018-05-28 19:29:23
【问题描述】:
这是我在自己的班级中制作的第一个程序。它旨在执行一次可转让的选举;现在我需要得到ArrayList<Candidate> 的Candidate 对象。在构造函数内部,这个过程工作得很好;但是,一旦我尝试使用访问器方法,就会返回一个空的ArrayList。这是代码:
import java.util.*;
public class Election {
public ArrayList<Candidate> candidates = new ArrayList<Candidate>();
Election(int numVotes) {
String name;
ArrayList<Candidate> candidates = new ArrayList<Candidate>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the candidates you want in the election.");
System.out.println("Enter -1 once you have listed all the candidates.");
System.out.print("Start entering candidates: ");
name = keyboard.nextLine();
while (!name.equals("-1")) {
candidates.add(new Candidate(name));
System.out.print("Ok, enter a new candidate or -1: ");
name = keyboard.nextLine();
}
//Works fine here
}
public ArrayList<Candidate> getCandidateList() {
//Keeps returning empty list
//System.out.println(candidates);
return this.candidates;
}
}
【问题讨论】: