2016-04-30 4 views
0

Как мне заставить программу обходить назад с начала, если выбран неправильный номер? Я не уверен, что я делаю неправильно. Я попытался if с, do while с, while с, и 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

Вы находитесь на правильном пути, но вы должны положить Console.ReadLine внутри время цикла и break из цикла только тогда, когда значение пользователя совпадает.

Что-то вроде этого псевдокода:

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);     
     } 

    } 
Смежные вопросы