2012-03-04 50 views
0

我是相當新的Java編程...但是這真的讓我難住了,我搜索了一會兒,我無法找到一個明確的答案,我一直在尋找的......但讓我們說我有兩種方法如何從另一種方法中的一個方法調用整數?

public static void program1 (String[] args) { 
    Integer intMoney; 
    intMoney = 500; 
} 

public static void program2 (String[] args) { 
    String strYes; 
    strYes = JOptionPane.showInputDialog("type yes to subtract 100"); 
    if((strYes.equals("Yes") || (strYes.equals("yes")))) { 
    /*((This is where I call the intMoney from program1) */ - 100; 
    }else{ 
     JOptionPane.showMessageDialog(null, "Thats not yes!"); 
    } 
} 

而且這裏是我得到真正卡住..說我有這樣程序1的另一種方法,但在另一種方法在程序1哪能呼籲intMoney價值?

比方說,我有一個程序,並且我想intMoney在一個單獨的方法中聲明,以便當方法program2重複時,intMoney值不會更改,並且當再次調用該方法時它將會相同。

+0

不介意;在if語句中,支持在 - 100 – user1247717 2012-03-04 05:30:02

+0

之後,您可以輕鬆編輯您的文章以糾正錯誤。我們大多數人都畏懼看到類似的東西。 – 2012-03-04 05:38:19

回答

0

你可以用」接入訪問,因爲it't作用域的方法在程序1變量。你應該這樣做:

public class Foo { 
    public static Integer intMoney; 

    public static void program1(String[] args) { 
     intMoney = 500; 
    } 

    public static void program2(String[] args) { 
     String strYes; 
     strYes = JOptionPane.showInputDialog("type yes to subtract 100"); 
     if ((strYes.equals("Yes") || (strYes.equals("yes")))) 
     { 
      Integer i = intMoney; 
      Integer x = i - 100; 

     }else{ 
      JOptionPane.showMessageDialog(null, "Thats not yes!"); 

     } 
    } 
} 

當然,現在你需要首先調用program1才能設置變量。你也可以像這樣啓動它public static final Integer intMoney = 500;

此外,有什麼用字串[] args參數,如果你不使用它們的?

+0

你的if語句到底分號......請更正.. – 2012-03-04 05:37:23

+0

,不應該他使用一個int變量,而不是整數的? – 2012-03-04 05:37:37

+0

@ShashankKadne Thx,修正。 – ebaxt 2012-03-04 05:39:31

2

首先你的程序是完全出於有這麼多錯誤規章制度:

  1. intMoney具有功能scope.So,它不能從功能程序1()外部調用。您必須從此函數返回值才能在另一個函數中使用。
  2. 在你如果你正在檢查2條件由||分離但兩者條件都一樣,請使用一個。

    public static int program1() { 
    Integer intMoney; 
    intMoney = 500; 
    return intMoney; 
    } 
    
    public static void program2() { 
    String strYes; 
    strYes = JOptionPane.showInputDialog("type yes to subtract 100"); 
    if((strYes.equals("Yes") || (strYes.equals("yes")))); { 
    program1() - 100 
    }else{ 
    JOptionPane.showMessageDialog(null, "Thats not yes!"); 
    
    } 
    } 
    
+0

如果program1返回一個int ...聲明intMoney爲int ...爲什麼要爲此創建一個Integer? – 2012-03-04 05:50:43

+0

有一個叫做autoboxing的概念,其中java會自動將Integer轉換爲int.By也可以使用int的方式。我只是儘量少修改代碼。 – 2012-03-04 05:56:04

+0

BTW代碼不是我的;;) – 2012-03-04 05:57:31

相關問題