2017-10-05 64 views
-1

我想知道如何在數組列表中添加具有用戶輸入的對象。我寫了一個名爲createEmployee()的方法,但我想知道如何在列表中執行此操作。所以我嘗試了employees.add(new Employee()),但我必須寫自己的意見。但是,我希望用戶編寫自己的輸入。我想要這樣的:employees.add(new Employee(identity, empname, empsalary)),但它不會工作。那麼我怎麼才能用自己的輸入來添加它,而createEmployee()方法是靜態的呢? 我試過如下:Java:如何使用用戶輸入在列表中添加對象?

public class Main extends ReusaxCorp { 

    public Main(String ID, String name, double grosssalary) { 
     super(ID, name, grosssalary); 
    } 

    public static void main(String[] args){ 
     createEmployee(); 
     ArrayList<Employee> employees = new ArrayList<Employee>(); 

     employees.add(new Employee()); 
    } 

    public static Employee createEmployee(){ 
     Scanner input = new Scanner (System.in); 
     System.out.print("Please enter the ID of the employee: "); 
     String identity = input.nextLine(); 
     System.out.print("Please enter the name of the employee: "); 
     String empname = input.nextLine(); 
     System.out.print("Please enter the gross salary of the employee: "); 
     double empsalary = input.nextDouble(); 

     Employee Employee = new Employee(identity, empname, empsalary); 
     return Employee; 
    } 
} 
+2

(你提到你不想使用創建員工的方法)什麼是你的問題嗎?你面臨什麼問題? –

+1

你想要一個帶有文本框的表單嗎?用戶可以輸入數據,然後保存到你的列表中? – FrankK

+0

當你調用你的方法時,你忽略了該方法的結果:'createEmployee();' – David

回答

1
public class Main extends ReusaxCorp { 

public Main(String ID, String name, double grosssalary) { 
    super(ID, name, grosssalary); 
} 

public static void main(String[] args){ 

    ArrayList<Employee> employees = new ArrayList<Employee>(); 

    Employee e = createEmployee(); 
    employees.add(e); 
} 

    public static Employee createEmployee(){ 
     Scanner input = new Scanner (System.in); 
     System.out.print("Please enter the ID of the employee: "); 
     String identity = input.nextLine(); 
     System.out.print("Please enter the name of the employee: "); 
     String empname = input.nextLine(); 
     System.out.print("Please enter the gross salary of the employee: "); 
     double empsalary = input.nextDouble(); 

     Employee Employee = new Employee(identity, empname, empsalary); 
     return Employee; 
    } 
} 
+0

謝謝,但你知道我沒有createEmployee方法是靜態的嗎? – JavaTeachMe2018

+1

如果你想使用'non static'方法,你需要創建一個Main類的實例,比如'Main m = new Main(...); m.createEmployee()' –

1

您可以使用構造直接,做這樣的事情在main方法

java.util.Scanner scanner=new java.util.Scanner(System.in); 
boolean addingEmployee=true; 
while(addingEmployee) 
{ 
System.out.println("Please enter the employee info ID,NAME,SALARY respectively "); 
employees.add(new Employee(scanner.next(),scanner.next(),scanner.nextDouble())); 
System.out.println("Employee has been added"); 
System.out.println("do you want to add new employee : Y,N"); 
if(scanner.next().charAt(0)=='N') {addingEmployee=false;} 
} 
相關問題