[英]Java - how to pass items from ArrayList in one class to constructor//getter and setter in another?
[英]how to pass ArrayList in a constructor to another class
我是java的新手,正嘗試在ArrayList上工作。 從Main方法,我想>將ArrayList傳遞給另一個類CustomerAcc。 我需要幫助,如何通過> ArrayList,然后如何在此處的客戶代碼類中獲取ArrayList
import java.io.*;
import java.util.*;
import java.lang.Object;
public class CustomerMain {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> custName = new ArrayList<String>();
ArrayList<String> custZip = new ArrayList<String>();
double count = 0;
boolean done = false;
System.out.print("Please enter Customer name or 'X' to exit: ");
Scanner in = new Scanner(System.in);
// Gets user input for name and zip code
while (in.hasNext() && !done) {
String checkInput = in.next();
if (checkInput.equalsIgnoreCase("X")) {
done = true;
}
else {
custName.add(checkInput);
System.out.print("Please enter Zip code: ");
custZip.add(in.next());
count++;
System.out.print("\nPlease enter Customer Name or 'X' to `enter code here`exit: ");
}
}
//Sending the user input data to CustomerAcc class
CustomerAcc custRecord = new CustomerAcc(custName, custZip, count);
}
}
CustomerAcc類:
public class CustomerAcc extends CustomerMain {
public static void CustomerAcc(String custName, String custZip, int count){
}
}
如果我很了解您想訪問另一個類中的ArrayList? 如果是這種情況,則可以在聲明私有ArrayList變量時使用getter和setter技術。
private ArrayList<String> custName = new ArrayList<String>();
private ArrayList<String> custZip = new ArrayList<String>();
public void setCustName(ArrayList custName){
this.custName = custName;
}
public ArrayList geCustName(){
return custName;
}
public void setCustZip(ArrayList custZip){
this.custZip = custZip;
}
public ArrayList geCustZip(){
return custZip;
}
將您的CustomerAcc
類的構造函數更改為:
public CustomerAcc(ArrayList<String> custName, ArrayList<String> custZip, int count){
}
另外,您還定義了custName和custZip為
ArrayList custName = new ArrayList();
ArrayList custZip = new ArrayList();
這是不正確的。 您必須在ArrayList中指定對象的類型(我想它們現在是字符串。)
定義如下:
ArrayList<String> custName = new ArrayList<>();
說話時的語法可以將構造函數代碼定義更改為-
public CustomerAcc(ArrayList<String> custName, ArrayList<String> custZip, int count){
}
查看您的代碼,您可能已經使用Map<String, String>
來存儲用戶名及其zip,而不是使用兩個列表。
單獨說明,您確定要構建單個CustomerAcc對象,將客戶列表及其郵政編碼作為輸入嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.