2012-12-10 103 views
1

這是我Q上&代碼上的Visual C++的遊戲有什麼辦法可以縮短這段代碼嗎?

   if (this->answer->Text == "2"){ 
       this->question->Text = "2+2?"; 
      } 
      else if (this->answer->Text == "4"){ 
       this->question->Text = "3+3?"; 
      } 
      else if (this->answer->Text == "6"){ 
       this->question->Text = "4+4?"; 
      } 
      else if (this->answer->Text == "8"){ 
       this->question->Text = "Finished!"; 
      } 
      else { 
       MessageBox::Show("Wrong!!"); 
      } 

有沒有縮短這個代碼?考慮使用數組?

回答

2

我不是一個Windows程序員,不知道是什麼的你 this->question->Text的類型,你沒有告訴我們,但是如果它是std::string或者其他可以轉換爲char *的東西,那麼這應該可以工作:

std::string t = this->answer->Text; 
this->question->Text = t == "2" ? "2+2?" 
        : t == "4" ? "3+3?" 
        : t == "6" ? "4+4?" 
        : t == "8" ? "Finished" 
        : ""; 
if (this->question->Text = "") MessageBox::Show("Wrong!!"); 
+0

錯誤man錯誤.. – JFetz2191

+0

@JFetz2191有什麼錯誤? – piokuc

+0

1 String t = this-> answer-> Text; 沒有合適的從「System :: String ^」到「System :: String」的用戶定義轉換 2.「==」也有錯誤..「沒有操作符匹配這些操作數,操作數類型是System :: String const char [2] – JFetz2191

0

嘗試使用switch case聲明。

+1

如何編碼? – JFetz2191

+1

我第二。 http://msdn.microsoft.com/en-us/library/k0t5wee3(v=vs.80).aspx – Kevin

+0

「該表達式必須是整型或類型的類型,其中有一個明確的轉換爲整數鍵入「,因此沒有用至少在這裏嘗試 –

1

您正在重複if (this->answer->Text ==this->question->Text =。只寫一次,並將條件和答案保存在std :: map中。

更新:

#include <map> 
#include <string> 

...

std::map<std::string,std::string> answers; 
answers["2"]="2+2"; // "configuration 
answers["4"]="3+3?"; 
//and so on 
std::string text=this->answer->Text; 
    // instead of if ... 
std::map<std::string,std::string>::const_iterator found=answers.find(text); 
if (found!=answers.end()) 
    this->question->Text = answers[text]; //once. Even better found->second 
else 
    MessageBox::Show("Wrong!!"); 
+0

如何編碼? – JFetz2191

+0

如何使用std :: map和那個? – JFetz2191

+0

查看答案更新 –

相關問題