If语句中未更改布尔值

时间:2016-02-18 16:50:52

标签: java android

我有两个类:GameScreen.java和KeyButton.java。有三个按钮是GameScreen类中引用的布尔值(是否按下它们),我想要与KeyButton类中的值进行比较。以下是相关代码:

GameScreen.java:

private void checkButtons() {
// Log.d("GameScreen","Note and Bar Intersected");

KeyButton keybutton = new KeyButton();

  if (B1Pressed == keybutton.getB1() && B2Pressed == keybutton.getB2() && B3Pressed == keybutton.getB3()) {
     // Log.i("GameScreenTest", "Correct");
      score++;
  } else {
     // Log.i("GameScreenTest - Result", "Wrong");
     // Log.i("GameScreenTest - Button Pressed", Boolean.toString(B1Pressed));
     // Log.i("GameScreenTest - Button Required", Boolean.toString(keybutton.getB1()));
  }
}

KeyButton.java:

public class KeyButton {

public boolean B1 = false;
public boolean B2 = false;
public boolean B3 = false;

Rectangles Rectangles = new Rectangles();
{

    //C major
    if (ScalesScreen.scaleType.equals("C")) {
    //C
    if (GameScreen.intersected == Rectangles.rectangle1) {
            B1 = false;
            B2 = false;
            B3 = false;
        }
    //D
    if (GameScreen.intersected == Rectangles.rectangle2) {
            B1 = true;
            B2 = false;
            B3 = true;
        }
    //E
    if (GameScreen.intersected == Rectangles.rectangle3) {
            B1 = true;
            B2 = true;
            B3 = false;
        }
    //F
    if (GameScreen.intersected == Rectangles.rectangle4) {
            B1 = true;
            B2 = false;
            B3 = false;
        }
...
public boolean getB1() {
    // TODO Auto-generated method stub
    //Log.d("Key 1", Boolean.toString(B1));
    return B1;
}

public boolean getB2() {
    // TODO Auto-generated method stub
    //Log.d("Key 2", Boolean.toString(B2));
    return B2;
}

public boolean getB3() {
    // TODO Auto-generated method stub
    //Log.d("Key 3", Boolean.toString(B3));
    return B3;
}

出于某种原因,B1,B2和B3值在GameScreen代码中返回false(来自keybutton.getB1()),导致分数在没有按下按钮时增加。因此,由于某种原因,布尔值不会更改为它们在KeyButton类中应该是什么。我该怎么做才能解决这个问题?

增加:

 for (Rect rect : rectangles) {

   if(Rect.intersects(rect, bar)) {
     //  Log.d("GameScreen", "intersected");
    intersected = rect;
    //  Log.d("Intersected", intersected.toString());
    checkButtons();

  }
}

1 个答案:

答案 0 :(得分:1)

每当调用CheckButton方法时,您都在创建一个新的KeyButton对象。每次都会重置标志的情况。

KeyButton keybutton = new KeyButton();

而不是使用Keybutton的全局实例或Make KeyButton 作为单个实例。因此,旗帜将持续存在。

public class KeyButton
{
    public boolean B1 = false;
    public boolean B2 = false;
    public boolean B3 = false;

    // Singleton
    private static KeyButton sInstance;
    private KeyButton () {}

    public static synchronized KeyButton getInstance()
    {
        if (sInstance == null)
        {
            sInstance = new KeyButton();
        }
        return sInstance;
    }

    ..
}