2017-10-11 66 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; 
    } 
}