这是我在自己的类中编写的第一个程序。它的目的是执行一次可转移的选举;现在我需要获取一个Candidate
对象的ArrayList<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;
}
}
https://stackoverflow.com/questions/50572508
复制相似问题