到目前为止,我上课了:
NaN
我有一个测试器类,其中有一个要将对象添加到的数组。到目前为止,测试人员的课程是:
public class Candidate
{
// instance variables
private int numVotes;
private String name;
// Constructor for objects of class Candidate
public Candidate(String name, int numVotes)
{
// initialize instance variables
this.name = name;
this.numVotes = numVotes;
}
public String getName()
{
return name;
}
public int getVotes()
{
return numVotes;
}
public void setVotes(int n)
{
numVotes = n;
}
public void setName(String n)
{
name = n;
}
public String toString()
{
return name + " received " + numVotes + " votes.";
}
}
到目前为止,我已经尝试过
public class ElectionTesterV1
{
Candidate Candidate[] = new Candidate[5];
}
但是我迷失了错误的非法起始类型和所需的标识符。如何将具有相同名称,然后带有数字的相同格式的对象添加到数组中。我应该使用数组,而不是arraylist
答案 0 :(得分:0)
您的数组为Candidate[]
,因此它需要保存Candidate
的实例。可以使用Candidate
和String
(根据构造函数)实例化int
类。
注意:我将阵列名称更改为candidates
(复数)以帮助区分用法。
您可以通过以下方式将其添加到阵列中:
// create the array
Candidate[] candidates = new Candidate[5];
// add the first person
candidates[0] = new Candidate("John Smith", 5000);
所以测试类可能如下:
public class ElectionTesterV1
{
// array of Candidate objects called candidates
Candidate[] candidates = new Candidate[5];
candidates[0] = new Candidate("John Smith", 5000);
candidates[1] = new Candidate("Mary Sue", 8765);
...
}