繁体   English   中英

如何使用另一个变量作为名称创建员工?

[英]How do I create an employee using another variable as a name?

我有这个代码,我正在使用另一个文件来存放员工 class 但我想使用 firstName + lastName 作为员工 object 的名称。 我想这样做,以便我可以使用此方法创建 Employee 对象并为每个对象设置唯一名称

package com.aho;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {

    public void createEmployee(String firstName, String lastName, int employeeCount){
        Employee firstName + lastName = new Employee();
    }

    public static void main(String[] args) {
        ArrayList <Employee> employeeList = new ArrayList<Employee>();
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter command: ");
        String command = input.nextLine();

        if(command.equals("Create new employee") || command.equals("create new employee")){
            System.out.println("\n" + "Input first name: ");
            String fName = input.nextLine();
            System.out.println("\n" + "Input last name: ");
            String lName = input.nextLine();
            createEmployee(fName,lName, employeeList.size());
        }else {
            System.out.println("Error");
        }
    }

}

如所写,您的代码无法编译。 您不能使用+来定义变量名。

看来你想要

Employee e = new Employee(fistName, lastName);

并且可能在 class 中创建一个字符串firstName + " " + lastName ...

然后,当您添加到列表时,您需要实际返回此实例的方法,例如

employeeList.add(createEmployee(fName, lName));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM