2016-04-30 41 views
0

如果選取的數字不正確,我該如何讓程序從頭開始循環?我不確定我做錯了什麼。我試過if S,do while S,while s和if else S:隨機數生成器失敗

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ArrayProblms 
{ 
    class Program 
    { 
     public static void Main(string[] args) 
     { 
      Console.WriteLine("Guess a number between 1 and 10: "); 
      RandomNumberGenerator(); 
      Console.ReadLine(); 
     } 

     public static void RandomNumberGenerator() 
     { 
      Random rand = new Random(); 
      int userValue = int.Parse(Console.ReadLine()); 
      int randValue = rand.Next(1, 11); 
      int attempts = 0; 

      if (userValue == randValue) 
      { 
       Console.WriteLine("You have guessed correctly!"); 
      } 
      while (userValue != randValue) 
      { 
       Console.WriteLine("You have guessed incorrectly"); 
       attempts++; 
       Console.WriteLine("You have made {0} incorrect guesses", attempts); 
       break; 
      } 
     } 
    } 
} 
+0

什麼是結束該程序的條件,什麼連連條件遍歷? –

回答

0

我會用do...while繼續要求用戶輸入新的號碼,直到他猜對了。下面

例子:

public static void RandomNumberGenerator() 
{ 
    Random rand = new Random(); 

    int randValue = rand.Next(1, 11); 
    int attempts = 0; 

    // do...while cycle to ask user to enter new value each time the used has been wrong 
    do 
    { 
     // read user input 
     int userValue = int.Parse(Console.ReadLine()); 

     // if user guessed correct 
     if (userValue == randValue) 
     { 
      Console.WriteLine("You have guessed correctly!"); 
      // go away from do...while loop 
      // it will stop asking user and will exit from the method 
      break; 
     } 

     // if user has been wrong 
     Console.WriteLine("You have guessed incorrectly"); 
     // increment attempts count 
     attempts++; 
     Console.WriteLine("You have made {0} incorrect guesses", attempts); 
    } 
    // and repeat until user guessed correctly 
    while(userValue != randValue) 
} 
+1

'試試這個:'沒有解釋任何東西。我們是否必須逐行比較代碼才能看到您已修復的問題? – Eser

+0

我發表了一段評論來描述示例代碼的功能。我希望這會有所幫助 – MaKCbIMKo

0

你在正確的軌道上,但是你需要把一個while循環中的Console.ReadLinebreak圈外只有當用戶的值匹配。

事情是這樣的僞代碼:

Generate random number 
while (true) { 
    Get value from user 
    If it matches, break 
} 
1

你應該把int userValue = int.Parse(Console.ReadLine());內環路和檢查每次迭代的輸入。 break必須是唯一的,如果userValue == randValue

public static void RandomNumberGenerator() 
    { 
     Random rand = new Random(); 

     int randValue = rand.Next(1, 11); 
     int attempts = 0; 


     while (true) 
     { 
      int userValue = int.Parse(Console.ReadLine()); // input inside the loop 
      if (userValue == randValue) // checking inside the loop 
      { 
       Console.WriteLine("You have guessed correctly!"); 
       break; 
      } 

      Console.WriteLine("You have guessed incorrectly"); 
      attempts++; 
      Console.WriteLine("You have made {0} incorrect guesses",   attempts);     
     } 

    }