gpt4 book ai didi

java - ArrayList 访问器方法不返回任何值

转载 作者:行者123 更新时间:2023-12-02 02:07:22 24 4
gpt4 key购买 nike

这是我在自己的类(class)中制作的第一个程序。它旨在执行单一可转让选举;现在我需要获得一个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;
}
}

最佳答案

public ArrayList<Candidate> candidates = new ArrayList<Candidate>();
Election(int numVotes)
{
String name;
ArrayList<Candidate> candidates = new ArrayList<Candidate>();
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

您正在创建一个不同数组列表并“隐藏”candidates成员变量。应该是

    this.candidates = new ArrayList<Candidate>();

关于java - ArrayList 访问器方法不返回任何值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50572508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com