2013-01-23 69 views
0

如果我想讓程序生成一個隨機數,然後re-read/loopelse if statement,直到它找到與此類似的語句,如果(button1.Text == ""),該隨機數只需要去高達9創建一個隨機循環,直到一個語句爲真

這是我的代碼,

private void button1_Click(object sender, EventArgs e) 
    { 
      var rc = new Random(); 
      storeRI = rc.Next(1, 9); 

      if (storeRI == 1) 
      { 
       if (button1.Text == "") 
       { 
        button1.Text = "X"; 
       } 
       else 
       { 
        //Need to generate another random number 
        //And read the else if statement again... how? 
       } 

      } 

      else if (storeRI == 2) 
      { 
       if (button1.Text == "") 
       { 
        button1.Text = "X"; 
       } 
       else 
       { 
        //Need to generate another random number 
        //And read the else if statement again... how? 
       } 

      } 
+1

檢查:http://stackoverflow.com/questions/10688044/filling-a-array-with-uniqe-random-數字之間的0-9之間的尖銳 – Dejo

+2

我真的不明白這段代碼的目的。 – daryal

+0

我想到的第一件事是'while循環'。然後,我瀏覽並查看其他人的回答,以及賓果!我們有同樣的想法。 'while(I_havent_find_the_answer)do' – alont

回答

2
private void button1_Click(object sender, EventArgs e) 
{ 
     var rc = new Random(); 
     do 
     { 
     storeRI = rc.Next(1, 9); 

     if (storeRI == 1) 
     { 
      if (button1.Text == "") 
      { 
       button1.Text = "X"; 
      } 
     } 

     else if (storeRI == 2) 
     { 
      if (button1.Text == "") 
      { 
       button1.Text = "X"; 
      } 
     } 
     } while (button1.Text == ""); 
} 
+0

謝謝!正是我需要的! –

+0

沒問題,隨時 –

1

if語句在while()循環。然後有執行break;語句來終止循環一個contidion:

while(button1.Text == "") 
{ 
    if (storeRI == 1) 
    { 
     if (button1.Text == "") 
     { 
      button1.Text = "X"; 
     } 
     else 
     { 
      //Need to generate another random number 
      storeRI = rc.Next(1, 9); 
     } 

    } 

    else if (storeRI == 2) 
    { 
    ... 
    } 
    else 
     break; 
} 
1
var rc = new Random(); 
int[] numbers = { 1, 2 }; // numbers from your if..else blocks 

do { 
    storeRI = rc.Next(1, 9); 

    if (!numbers.Contains(storeRI)) 
     break; // not matched any if..else block 

    if (button1.Text == "") 
    { 
     button1.Text = "X"; 
     break; // set text and break loop 
    } 

} while(true); // generate new number and do check again