2013-04-16 73 views
0

我正在使用Sapphire on Steel上的Visual Basic添加語言Ruby來編譯和運行我的代碼。我正在爲一個學校項目製作一個二十一點計劃,無論出於什麼原因,我無法準確地找到擺脫我創建的循環的方式。 Loop將繼續運行代碼,詢問用戶他們是否要點擊或站立,並根據用戶輸入的信息來判斷他們是否繼續點擊或結束。任何和所有的意見,將不勝感激。感謝您的時間。我被困在我的循環中,我該如何退出?

while choice != "stand" 

        #This is the loop that I can not find my way out of 
     while choice != "hit" || choice != "stand" 

      puts "Would you like to hit or stand?" 
      choice = gets.chomp! 
      choice.downcase 

      if choice == "hit" 
       puts "You have chosen to hit \n\n" 
       player.drawCard(myDeck) 
       puts "Player's Hand: \n" 
       player.showHand() 
       puts "\n" 
       puts "Player Score: \n" 
       player.determineScore() 
       puts player.printScore() 
       puts "\n \n" 
      elsif choice == "stand" 
       puts "You have chosen to stand \n\n" 
       puts "Player's Hand: \n" 
       player.showHand() 
       puts "\n" 
       puts "Player Score: \n" 
       player.determineScore() 
       puts player.printScore() 
       puts "\n \n" 
      else 
       puts "Your choice is not acceptable please choose again" 
      end 

     end 
+2

使用'&&'代替'||'。 – JJJ

回答

0

一個||如果A爲真或B爲真,B將返回真。

因此,例如,如果你的選擇是「重災區」你的代碼將變爲:

while false || choice != 'stand' 

將評估爲

while false || true 

這當然是正確的。

更改條件:

while !(choice=='hit' || choice=='stand') 

,你的問題應該消失。

+0

謝謝你的幫助! – user1457104

2

這將永遠是正確的:

choice != "hit" || choice != "stand" 

使用& &代替:

choice != "hit" && choice != "stand" 
1

正如其他人所指出的那樣,你while條件總是返回true。他們的回答適當地鼓勵你改變你的狀況。

但是,爲了使您的代碼更具可讀性,我建議使用until,它與while !(false)相同。

until choice == "hit" || choice == "stand" 
    # Code 
end 

這將使您的代碼更具可讀性,更「Rubyish」。

還有一種選擇是使用Array#include?這將允許您提供一系列選擇並查看玩家是否選擇了其中一種選擇。

until ['hit', 'stand'].include? choice 
    # Code 
end 

這樣一開始可讀性稍差,但如果您想添加更多選擇,則易於維護。