2017-01-02 59 views
-2

我的代碼似乎對我來說乾淨我不明白爲什麼它不起作用。Java:簡單的可變問題

有一個按鈕,它應該改變你點擊它時繪製的精靈(這一步工作),當你點擊它時,它也應該給我的變量planetCount加1,這一步的目的是得到繪製的星球精靈:

right.addListener(new ClickListener() { 
    public void clicked(InputEvent event, float x, float y) { 
     sound.play(0.2f); 

     if (planetCount <= 4) { 
      choixRegion.setRegion(choix2Region); 
      choix2Region.setRegion(choix3Region); 
      choix3Region.setRegion(choix4Region); 
      choix4Region.setRegion(choix5Region); 
      choix5Region.setRegion(choixRegion); 

     } else if(planetCount < 4){ 
      planetCount = planetCount + 1; 
     } else if(planetCount > 4){ 
      planetCount = 4; 
     } 
    } 
}); 

,問題是存在的,對於所有的行星選擇它給回報我同樣的屏幕(StartGame)總結一下,如果我有planetCount = 1,它應該返回我Itryon的屏幕,但不管planetCount值如何,它始終返回StartGame屏幕:

oui.addListener(new ClickListener() { 
    public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { 
     if(planetCount == 0){ 
      game.setScreen(new StartGame(game)); 
     } else if(planetCount == 1){ 
      game.setScreen(new Itryon(game)); 
     } else if (planetCount == 2){ 
      game.setScreen(new Nernel(game)); 
     } else if(planetCount == 3){ 
      game.setScreen(new Abela(game)); 
     } else if(planetCount == 4){ 
      game.setScreen(new StartGame(game)); 
     } 
     sound.play(0.2f); 
     music.stop(); 
     return true; 
    } 

那麼我的錯誤在哪裏?

+3

如果初始'if'條件是假的'其他if'位時,纔會執行。在你的情況下,'else if'分支永遠不會運行。 – assylias

+0

這取決於你想要什麼,但這將是一個選項。 – assylias

回答

0
 public void clicked(InputEvent event, float x, float y) { 

      // ... 

      if (planetCount <= 4) { 
       // ... 
       // when true, planetCount is not increased. 
       // You can try setting planetCount = 1 at start, 
       // And you'll get only Itryon's screen. 
      } 
      else if(planetCount < 4){ 
       planetCount = planetCount + 1; 
      } 
      else if(planetCount > 4){ 
       planetCount = 4; 
      } 

你可以簡單的修改方法如下:

 public void clicked(InputEvent event, float x, float y) { 

      sound.play(0.2f); 

      choixRegion.setRegion(choix2Region); 
      choix2Region.setRegion(choix3Region); 
      choix3Region.setRegion(choix4Region); 
      choix4Region.setRegion(choix5Region); 
      choix5Region.setRegion(choixRegion); 

      // You should think about below logic. 

      planetCount++; 

      if (planetCount > 4) { 
       planetCount = 4; 
      } 
    } 
0

的問題是關係到使用第一if else if結構。

在您的代碼中,您永遠無法運行第一條else if語句,因此計數器永遠不會遞增。

你可以寫這樣的事情:

right.addListener(new ClickListener() { 
     public void clicked(InputEvent event, float x, float y) { 

      sound.play(0.2f); 

      if (planetCount < 4) { 
       choixRegion.setRegion(choix2Region); 
       choix2Region.setRegion(choix3Region); 
       choix3Region.setRegion(choix4Region); 
       choix4Region.setRegion(choix5Region); 
       choix5Region.setRegion(choixRegion); 
       planetCount = planetCount + 1; 

      } 
     } 
    });