2015-08-14 29 views
1

我正在開發兩個獨立的程序,其中涉及來自每一方的方法調用。程序A是MyNoteCenter.java,程序B是SocketServer.java。在MyNoteCenter中包含一個方法調用來觸發SocketServer中的方法來下載資源,所以SocketServer中的計數器將遞增1.當我單擊MyNoteCenter中的按鈕下載時,它將聯繫SocketServer進行下載請求並增加如果SocketServer收到有效參數,計數器加1,但爲什麼我的計數器只增加一次?它只會運作良好,第一次我點擊下載按鈕,但是當我點擊第二次時,計數器仍呈現1增量計數器的方法不適用於java

這是我SocketServer的節目的一部分

public String getDownload() 
{ 
    int c = 0; 
    c = c + 1; 
    switch(software) 
    { 

     case "1" : 
      message = "ITune"; 
     // counter++; 
      break; 

     case "2" : 
      message = "ZoneAlarm"; 
     // counter++; 
      break; 

     case "3" : 
      message = "Winrar"; 
     // counter++; 
      break; 

     case "4" : 
      message = "Audacity"; 
     // counter++; 
      break; 

    } 

    JOptionPane.showMessageDialog(null,"Your download is\n" +message+ "\n the number of download is\n"+c); 
    return message; 

} 

這是方法在MyNoteCenter,該方法將被觸發後BTN2是單擊是下載按鈕,該runCC方法將聯繫SocketServer的方法下載

public static void runCC(String software,String id,String name,String job,String country) 
     { 
     SocketServer dc = new SocketServer(software,id,name,job,country); 
     String ServerReplyMessage = dc.getDownload(); 
     JOptionPane.showMessageDialog(null,"Downloading :\n" +ServerReplyMessage); 
     int answer = JOptionPane.showConfirmDialog(null, "Do you want to continue?", "Confirm",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); 
     if (answer == JOptionPane.NO_OPTION) 
     { 
      JOptionPane.showMessageDialog(null,"Please click close button"); 
     } 
     else 
     { 
      JOptionPane.showMessageDialog(null,"Please proceed"); 
     } 

http://codepad.org/ >>我全SocketServer的程序

回答

0

您每次運行該方法時都會重新初始化c

c應該是一個在類中定義的字段,每當你需要增加它或者評估它的當前值時它將保持值。

public class MyClass { 

    private int c = 0; 


    public String getDownload() { 
     c++; 

     switch case... 
    } 

} 
+0

聲明我的c變量爲全局變量? – doe

+0

@doe全球的班級是,但私人範圍內的班級 – andrewdleach

+0

但櫃檯保持不變,這裏是我的新修改程序http://codepad.org/W5TkxIpq。我不知道我是否遵循正確的指令,我已經對全局變量c變量進行了更改,而不是局部變量 – doe