2013-10-01 42 views
0

在我的程序的主要方法中,我有一堆掃描儀輸入,我已經通過參數傳入各種方法。 在這些不同的方法中,我已經完成了計算,創建了新的變量。 在我最後的方法中,我需要將這些新變量加在一起,但編譯器不會識別新變量,因爲它們只存在於其他方法中。我將如何去將新變量傳遞給我的最終方法?如何在java中的方法之間傳遞變量?

+1

你的方法返回的是'void'以外的東西嗎?否則,改變這可能是一個好的第一步。 –

+4

我建議你通過基礎教程。 – Maroun

+0

請顯示你的代碼 –

回答

3

而不是創造局部變量的創建類類變量的variables.The範圍是,他們是全球性的意義,你可以在任何地方訪問該類

4

變量的方法創建的是本地的方法和範圍僅限於那些變量只有方法。

所以去instance members,你可以在方法中共享。

如果你聲明瞭,你不需要在方法之間傳遞,在方法中更新這些成員。

scope

考慮,

public static void main(String[] args) { 
    String i = "A"; 
    anotherMethod(); 
    } 

您在下面的方法獲得一個編譯錯誤,如果您嘗試訪問我,因爲i是局部變量主要方法。您無法使用其他方法訪問。

public static void anotherMethod(){ 
     System.out.println(" " + i); 
    } 

你可以做的是,將該變量傳遞到你想要的地方。

public static void main(String[] args) { 
    String i = "A"; 
    anotherMethod(i); 
    } 

    public static void anotherMethod(int param){ 
     System.out.println(" " + param); 
    } 
+0

如果你想從代碼之外的某個地方將變量傳入主方法會怎樣? – santafebound

+1

@bluemunch如果你從命令行運行,那裏。如果是在eclipse中,你可以在運行配置 –

+0

酷。奇怪的是,我的實現甚至沒有使用主要方法,因爲參數完全從一個不同的程序傳遞到一個Map中。 – santafebound

1

您可以創建一個List並將它作爲參數傳遞給每個方法。最後,你需要遍歷列表並處理結果。

0

用新變量創建一個對象並返回它們的總和。 在您的方法中使用此對象進行新變量計算。 然後使用對象方法獲得新的變量

0

的總和你可以做這樣的事情:

public void doStuff() 
{ 
    //Put the calculated result from the function in this variable 
    Integer calculatedStuff = calculateStuff(); 
    //Do stuff... 
} 

public Integer calculateStuff() 
{ 
    //Define a variable to return 
    Integer result; 

    //Do calculate stuff... 
    result = (4+4)/2; 

    //Return the result to the caller 
    return result; 
} 

你也可以做到這一點(然後你可以檢索的變量calculatedStuff在類中的任何功能) :

public class blabla { 

    private Integer calculatedStuff; 

    public void calculateStuff() 
    { 
     //Define a variable to return 
     Integer result; 

     //Do calculate stuff... 
     result = (4+4)/2; 

     //Return the result to the caller 
     this.calculatedStuff = result; 
    } 

} 

但正如其他人所建議的那樣,我也很樂意推薦做一個基本的Java教程。