Java - 使用另一个类的变量作为方法参数

时间:2017-10-11 01:23:44

标签: java arraylist

在我的Main课程中,我有这段代码:

UUID uniqueID;

public void createEmployee(){       
    uniqueID = UUID.randomUUID(); 
    // ...
}

在我的班级Corporation中,有一个名为promoteEmployee的方法,它应该接收唯一ID作为参数。这是可能的,当是的时候,怎么样?

public void promoteEmployee(uniqueID){
   // it doesn't recognize uniqueID as argument
}

我也有方法sortEmployees,它按字母顺序对ArrayList进行排序,如果两个名字相等,那么应该先打印出薪水较高的员工。它按字母顺序对列表进行排序,但不检查薪水是否更大。我需要改变什么?

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

public void sortEmployees(){
    Collections.sort(employees, (p1, p2) -> p1.name.compareTo(p2.name));
    for(Employee employee: employees){
        Comparator.comparing(object -> employee.name).thenComparingDouble(object -> employee.grossSalary);
        System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: "+employee.name + END_OF_LINE + "Salary: " + employee.grossSalary);
        System.out.println(""); // just an empty line
    }
}

2 个答案:

答案 0 :(得分:1)

将方法更改为有效的Java代码

public void promoteEmployee(UUID uniqueID){

但是因为它甚至看起来像是一个字段,为什么要传递这个值呢?

至于排序见 Implementing Java Comparator

答案 1 :(得分:1)

使用classname.method(arg)语法将变量从一个类传递给另一个类。

    public class JavaTeachMe2018

{
    //variable in other class to be passed as a method argument
    public static int startID = 0;

    public static void main(String[] args)
    {
        // we are passing startID to anouther class's method
        String[] currentEmployees = Corporation.createEmployee(startID);
        System.out.println("Welcome " + currentEmployees[1] + " to the company as employee number " + currentEmployees[0]);
    }
}// end class teachme

这是第二类

 import java.util.Scanner;
public class Corporation
{

    public static int createId(int startID)
    {
            // create unique id
            int uniqueID = startID + 1;
            return uniqueID;
    }
    public static String[] createEmployee(int startID)
    {

        // assign a variable to the return of the createId call
        int employeeNumber = createId(startID);
        System.out.println("Your assigned employee number is " + employeeNumber);
        // get employee name
        Scanner stdin = new Scanner(System.in);
        System.out.print(" Enter Your Name : ");
        String employeeName = stdin.nextLine();
        String employees[] = {Integer.toString(employeeNumber), employeeName};
        return employees;
    }
}