是否可以使用ArrayList的计数来实现它? 假设我的构造函数允许传递一个名称以创建一个对象,我可以向用户询问该名称,然后使用它来执行此操作然后将其传递给已创建的ArrayList吗?
我觉得我无法解释我的意思,英语不是我的第一语言,抱歉。 :)
public class Voter
{
private String name;
private ArrayList<Voter> voters;
public Voter(){
this.name = "";
voters = new ArrayList();
}
public Voter(String name)
{
this.name = name;
voters = new ArrayList<>();
}
public void add(Voter v)
{
if (!this.voters.contains(v))
{
this.voters.add(v);
}
}
}
public static void main(String[] args)
{
Voter v1 = new Voter("Admin");
Voter v = new Voter();
v.add(v1);
displayMenu();
int option = getInt("Enter Option:", 0, 3);
while (option != END)
{
if (option == 1)
{
doOption1();
int count = v.countArray(v);
}
}
}
public static void displayMenu()
{
System.out.println("\nSample Menu of Options");
System.out.println("0. Exit this menu");
System.out.println("1. Option 1");
}
public static void doOption1()
{
System.out.println("Please, enter the below details to register for
voting system.");
System.out.println("Full name");
String name = keyboard.nextLine();
//THIS IS WHERE I WANT TO CREATE A NEW OBJECT AND PUT IT AS AN ELEMENT OF
//MY Voter ARRAYLIST
}
public static int getInt(String prompt, int min, int max)
{
System.out.print(prompt);
int value = keyboard.nextInt();
while ((value < min) || (value > max))
{
System.out.println("Invalid - [" + min + "," + max + "] only");
System.out.print(prompt);
value = keyboard.nextInt();
}
keyboard.nextLine();
return value;
}
答案 0 :(得分:0)
在您的当前算法已经到位的情况下,为了将项添加到ArrayList
对象的Voter
,您只需首先重建{{1}的方法定义1}}到下面的方法。
doOption1
完成此操作后,您需要更改此代码:
public static void doOption1(Voter voter){
System.out.println("Please, enter the below details to register for voting system.");
System.out.println("Full name");
String name = keyboard.nextLine();
voter.add(new Voter(name)); // you could validate name before constructing the object if you see fit.
}
到此:
while (option != END){
if (option == 1){
doOption1();
int count = v.countArray(v);
}
}