2017-10-11 73348 views
2

在我Main类我有这样一段代码:爪哇 - 从另一个类使用变量,方法参数

UUID uniqueID; 

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

在我Corporation类有一个名为promoteEmployee方法,它应该接受UNIQUEID作为参数。这是可能的,如果是的话,如何?

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 
    } 
} 

回答

1

变化的方法是有效的Java代码

public void promoteEmployee(UUID uniqueID){ 

但它甚至似乎是一个领域,为什么传递价值可言?

至于排序看到 Implementing Java Comparator

+0

谢谢。我已经看过实现Java比较器的帖子,但它并没有真正帮助我.. – JavaTeachMe2018

+0

以及尝试搜索更多资源以了解如何实现Comparator例如https://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/ esp。 * 4。使用比较器对对象进行排序* –

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; 
    } 
}