2017-10-28 60 views
-1

我有一個程序,它是一個客戶/服務器遊戲問題遊戲。我已經做到了,只要計算客戶/服務器在遊戲結束時發送終止命令的各種情況。現在在Java中以函數結束後獲取參數值更改爲持久

,我的問題是,我有一組的原始int points, attempts, correct這是由客戶端從服務器中的String如下解讀:

注:我做知道,Java功能通過參數,而不是引用,並指定函數內部的值將不會改變原來的的值。

int points = accepted = correct = 0; 
String inbound = check (inbound, points, accepted, correct); 
System.out.println(points); // Displays value of 0, when expecting > 0 

private static String check (String str, int points, int attempts, int correct) { 

    // Expect Q QuestionString 
    if (str.substring(0,1).equals("Q")) { 
     //System.out.println("This is the question."); 
     return str.substring(2, str.length()); 
    } 

    String[] input = str.split(" "); 

    // Expect EX # # # 
    if (input[0].contains("EX")) { 
     points = Integer.parseInt(input[1]); 
     attempts = Integer.parseInt(input[2]); 
     correct = Integer.parseInt(input[3]); 
     return "EX"; 
    } 

    // Expected strings: Correct..., Incorrect. 
    return str; 
} 

我不確定如何解決此問題而不危害封裝或阻礙其他概念。

+0

我想通過「危及封裝或阻礙其他概念「你的意思是創建一個包裝類?如果出現這種情況,請避免「封裝或阻礙其他概念」,因爲在這種情況下IMO是最佳選擇。其他選擇包括製作「點數」,「正確」和「嘗試」等級變量併爲其分配值。 – Sweeper

回答

0

創建一個包裝類來包含這三個整數參數,然後只是將該包裝的一個實例傳遞給check方法,然後在該方法中修改其內容。

例如:

public class Wrapper 
{ 
    private int points; 
    private int attempts; 
    private int correct; 

    public int getPoints() { 
     return points; 
    } 

    public void setPoints(int points) { 
     this.points = points; 
    } 

    public int getAttempts() { 
     return attempts; 
    } 

    public void setAttempts(int attempts) { 
    this.attempts = attempts; 
    } 

    public int getCorrect() { 
     return correct; 
    } 

    public void setCorrect(int correct) { 
     this.correct = correct; 
    } 
} 

從而代碼的第一部分將變成:

Wrapper wrapper = new Wrapper(); 
String inbound = check (inbound, wrapper); 
System.out.println(wrapper.getPoints()); 

和您的check方法變爲:

private static String check (String str, Wrapper wrapper) { 
     ... 
     ... 
     if (input[0].contains("EX")) { 
      wrapper.setPoints(Integer.parseInt(input[1])); 
      wrapper.setAttempts(Integer.parseInt(input[2])); 
      wrapper.setCorrect(Integer.parseInt(input[3])); 
      return "EX"; 
     } 
     ... 
     ... 
} 
+1

謝謝,我已經添加了一個對象類的功能,我正在使用它來保存這些數據。 –