2015-10-03 11 views
-1

У меня возникли проблемы с моим кодом. Я должен сделать простую игру выбора, и мне нужно ее иметь, чтобы, если пользователь вводит неверный параметр, он приостанавливает историю до тех пор, пока не выберет правильный ответ. Я попробовал обернуть все это через некоторое время (1 == 1) и ввести неверные ответы в консольное окно, и он напечатал «Это был не вариант» бесконечно. Как я могу это исправить? Благодарю.Не соблюдайте неправильный ввод пользователя до получения правильного ввода

  // First choice, scene 1 if-statements 
     while (1 == 1) 
     { 
      String firstScene = Console.ReadLine(); 
      firstScene = firstScene.Trim(); 
      String firstChoice = firstScene.ToLower(); 
      Console.WriteLine(); 

      if (firstChoice == "rudely") 
      { 
       assholeFactor++; 
       Console.WriteLine(">>\"You're damn right it was! We've been working on this for years. I thought you'd be happy that all those hours at the office actually amounted to something.\" (Douche factor increased)"); 
       break; 
      } 
      if (firstChoice == "nicely") 
      { 
       niceFactor++; 
       Console.WriteLine(">>\"No, it wasn't silly. I can see where you're coming from. I suspect there will be a lot of people with those same type of questions upon the release of the first model.\" (Nice factor increased)"); 
       break; 
      } 
      if (firstChoice == "silence") 
      { 
       judgement--; 
       Console.WriteLine(">>You sip your wine and say nothing. (Judgement decreased)"); 
       break; 
      } 
      if (firstChoice != "rudely" || firstChoice != "nicely" || firstChoice != "silence") 
      { 
       Console.WriteLine("That wasn't an option."); 
       continue; 
      } 
     } 
+2

Где цикл? – Steve

+0

Цикл while? Я удалил его, но это было до строки if (firstChoice). – crin

+1

Это просто ошибка, вы должны проверить firstChoice2, а не firstChoice. Если вы не выбрали хорошие имена переменных, вы добавите ошибки. –

ответ

0

Вы должны перечитать, введенные пользователем в переменную в петля перед проверкой это условие:

var input = ReadLine(); 
while (true) // or some other condition 
{ 
    if (input=="...") { } ... 

    input = ReadLine(); // again 
} 

Кроме того, я loled на assholeFactor++

+0

Лучше сделайте это, пока вам нужен один цикл цикла. – khlr

+0

Хорошо, поэтому я применил это предложение (неправильно, я уверен), но когда я ввел недействительный ответ, в первый раз он не возвратил никакого сообщения вообще. Я попытался снова в том же окне консоли, и он сказал: «Это не вариант». Когда я попытался ввести правильный ответ, он продолжал говорить: «Это не вариант». – crin

+0

Отладка через ваш код в пошаговом режиме. Я на 100% уверен, что вы обнаружите, что ваш поток испорчен. – SimpleVar

2

Вы можете сделать так , В принципе, вы сохраняете флаг для управления циклом. Продолжайте, пока не получите правильный ввод. Остановите цикл, установив флаг, как только вы получите правильный ввод.

string firstChoice = "getInputFromUser...."; 
var isCorrectInput = false; 

do 
{ 
    if (firstChoice == "rudely") 
    { 
     isCorrectInput = true; //stop further loop iteration 
     assholeFactor++; 
     ..... 
    } 
    else if 
     ... //set isCorrectInput as well 
    else 
    { 
     //if input didn't match options, continue loop 
     Console.WriteLine("That wasn't an option. Enter again..."); 
     firstChoice = Console.ReadneLine(); // 
    } 
} while(!isCorrectInput); 
0

Вы можете использовать флаг для проверки каждого цикла, если вопрос был правильно ответил. Что-то вроде этого:

var answered = false; 
while(!answered) // Loop until the question has been correctly anwered 
{ 
    var firstChoice = ReadLine(); 
    if (firstCoice == "rudely") 
    { 
     assholeFactor++; 
     Console.WriteLine(">>\"You're damn right it was! We've been working on this for years. I thought you'd be happy that all those hours at the office actually amounted to something.\" (Douche factor increased)"); 
     answered = true; // Question answered --> shouldn't keep asking 
    } 
    else if... 
    else 
    { 
     Console.WriteLine("That wasn't an option."); 
    } 
} 
0

Вы можете сделать что-то вроде:

Dictionary<string,Tuple<string,Action>> Choices = new Dictionary<string, Tuple<string, Action>>(); 
    int assholeFactor = 0; 
    int niceFactor = 0; 
    int judgement  = 0; 

    Choices.Add("rudely" , new Tuple<string, Action>("You're damn right it w.."   ,() => assholeFactor++)); 
    Choices.Add("nicely" , new Tuple<string, Action>("No, it wasn't silly. I ca.."  ,() => niceFactor++ )); 
    Choices.Add("silence", new Tuple<string, Action>("You sip your wine and say nothing.",() => judgement-- )); 

    do 
    {   
     string option = Console.ReadLine(); 
     if (Choices.ContainsKey(option)) 
     { 
      Console.Out.WriteLine(Choices[option].Item1); 
      Choices[option].Item2();      
      break; 
     } 
     Console.WriteLine("That wasn't an option."); 
    } while (true); 
Смежные вопросы