2017-10-05 3 views
-1

배열 목록에 사용자 입력이있는 객체를 추가하는 방법을 알고 싶습니다. 나는 createEmployee()이라는 방법을 썼지 만, 목록에서 그것을하는 법을 알고 싶습니다. 그래서 employees.add(new Employee())으로 시도했지만 거기에 직접 입력해야합니다. 그러나 사용자가 자신의 의견을 직접 써야합니다. 나는 이런 식으로 싶습니다 : employees.add(new Employee(identity, empname, empsalary)),하지만 작동하지 않습니다. 그래서 어떻게 내 자신의 입력과 함께 메서드를 createEmployee() 정적없이 추가 할 수 있습니까? 나는 다음과 같은 시도 :자바 : 사용자 입력이있는 목록에 개체를 추가하려면 어떻게해야합니까?

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 m = new Main (...);과 같이 Main 클래스의 인스턴스를 생성해야합니다. m.createEmployee()' –

1

당신이 주요 방법처럼 뭔가를 직접 생성자를 사용할 수

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;} 
} 
관련 문제