2012-04-04 57 views
0

在我的一個方法中有一個名爲「量」的變量,但我需要在另一個方法中引用它。我不確定使用的語法。初始化在方法外部使用的實例變量

下面是代碼:

public static void startup() 
{ 
    String message = "Welcome to Toronto Mutual!"; 
    //prompts user to enter their employee ID 
    String logIn = JOptionPane.showInputDialog("Please enter your employee `enter code here`ID."); 
    int employeeID = Integer.parseInt(logIn); 

    String input = JOptionPane.showInputDialog("Please enter the transaction `enter code here`type, bank ID and amount all separated by a comma."); 
    input=input.toUpperCase(); 
    if (input.equals("END")){ 
     JOptionPane.showMessageDialog(null,"Goodbye."); 
     System.exit(0); 
    } 
    else 
    { 
     int balance = 100; 
     String []transaction = new String[3]; 
     transaction = input.split(","); 
     String type = transaction[0]; 
     int bankID = Integer.parseInt(transaction[1]); 
     type=type.toUpperCase(); 
... // there's more but it's irrelevant 

如何使用變量「量」和「bankID」的方法之外?

+0

我看不到代碼'amount'。 – kasavbere 2012-04-04 23:49:07

+1

代碼中沒有看到「金額」和「bankID」。但是如果你真的需要用另一種方法引用它,只需在啓動()方法之外初始化它即可。 '私人字符串的數量;'並在這種方法中做任何你想要的。你可以從另一種方法閱讀它 - 只要確保你按照正確的順序來調用它。 – 2012-04-05 00:47:15

+0

或者將其作爲參數傳遞給需要它的方法。 – 2013-06-02 16:55:26

回答

1

兩種方式:

  1. 通行證amount其他方法通過參數

    private void otherMethod(int amount) {...}

  2. 創建一個實例變量,這樣就可以在類範圍

    內訪問private int amount;

    如果你走這條路線,最好使用getter和setter。

    public int getAmount() { 
        return amount; 
    } 
    
    public void setAmount(int amount) { 
        this.amount = amount; 
    }