[英]Creating next object and placing it in an ArrayList
Okey,所以我感覺到解釋我的意思可能非常困難,但是,我要嘗試。 所以,基本上我想要做的是創造一個下一個對象 ,並使用用戶輸入其放置在一個ArrayList。
是否可以使用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;
}
在使用當前算法的情況下,要將項目添加到Voter
對象的ArrayList
要做的就是首先將doOption1
的方法定義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);
}
}
對此:
while (option != END){
if (option == 1){
doOption1(v); // notice the argument
int count = v.countArray(v);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.