在以Java结尾的函数之后,使参数的值更改保持不变

时间:2017-10-28 14:15:43

标签: java

我有一个程序,它是一个客户/服务器游戏问题游戏。我已经考虑到客户/服务器在游戏结束时发送终止命令的各种情况。

现在,我的问题是我有一组原始int points, attempts, correct,它们由客户端从服务器读取,如下所示:

N.B。我知道 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;
}

我不确定如何在不危及封装或阻碍其他概念的情况下解决此问题。

1 个答案:

答案 0 :(得分: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";
        }
        ...
        ...
}