2016-01-13 53 views
0

我有一個可能非常基本的問題,但我似乎無法在堆棧中找到它(並且我發現的東西非常複雜),所以如果它已經出來,我很抱歉那裏有地方。如何調用並執行方法

我正在用java編寫一個紙牌遊戲,我想將一張繪製新卡片的代碼移動到一個單獨的方法中,以便我可以隨時調用它,而不是使用同一段代碼每當我需要它時,會一再出現。

唯一的問題是我不知道使用什麼類型的方法或如何調用它,因爲它不會返回任何東西,只是做一堆代碼。

這是我的代碼片,如果這有助於顯示我打算做的事情。

if (event.getSource() == hit && endOfRound == false) { 
    Continue = true; 
    while (Continue == true) //If the random number has been drawn before, loop the random number generator again 
    { 
     cardID = (int) RandomNumber.GetRandomNumber(52); 
     if (cardsLeft[cardID] == true) //If a new card is drawn, continue normally 
     { 
      Continue = false; //Stop the loop that draws a new card 
      cardsLeft[cardID] = false; //save that the card was drawn 
      stay.setBackground(Color.green); 

      plyrSum += BlackJack.value(cardID); //add value to sum 
      plyrSumLabel.setText("Your sum: " + plyrSum); //display new sum 
      cardLabel[plyrCardCounter].setIcon(cardImage[cardID]); //Display card 

      plyrCardCounter++; 
      if (cardID >= 48) //record how many aces are in the hand so the program knows how many times it can reduce the sum. 
       plyrAceCounter++; 
      while (plyrSum > 21 && plyrAceCounter > 0) //If bust, reduce the value of an ace by 10 (from 11 to 1). 
      { 
       plyrSum -= 10; 
       plyrSumLabel.setText("Your sum: " + plyrSum); 
       plyrAceCounter--; 
      } 

      if (plyrSum > 21) //Automatically end the round if someone busts (player) 
      { 
       stay.doClick(); 
      } 
     } 
    } 
} 
+0

分解一個複雜的過程分成一系列更小的,獨立的,並且在邏輯上不同的步驟是,一般地,總是一個好主意。在像Java這樣的面向對象的語言中,這應該作爲對象模型的自然結果發生。我注意到你正在寫一個紙牌遊戲,所以看起來自然的域對象似乎是'Card',但你的項目似乎並沒有面向對象的抽象抽象。 – scottb

回答

0

聲明一個方法的drawcard()返回void。現在複製中的塊,如果並將其粘貼到方法中。 然後重寫如果部分:

if (event.getSource() == hit && endOfRound == false) drawCard(); 
+0

非常感謝,但是我怎麼稱呼這個方法呢?公共靜態無效?因爲這似乎並不奏效。 (錯誤消息:令牌上的語法錯誤「void」,@ expected)我做錯了什麼? – Jojo

+0

void drawCard(){/ * code * /} –

+0

這很奇怪,因爲當我瀏覽它時,我確信我已經完成了這個操作,但不知何故,我收到另一條錯誤消息,提示「此行有多個標記 \t - 的drawcard不能被解析爲一個 \t型 \t - 語法錯誤令牌「作廢」,新 \t預計」 – Jojo