2016-07-15 3 views
0

Я пытаюсь создать приложение консоли Table Table в сообществе Visual Studio 2015 с использованием Visual C#, но оператор if не оценивается должным образом. Я начал отлаживать (тестировать) мое консольное приложение, но оператор if не был правильно оценен в последних трех вопросах. Может кто-нибудь помочь? Вот мой код:Почему утверждение if на Visual C# не оценивается должным образом?

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

    namespace xTables 
    { 
     class Program 
     { 
      static void Main(string[] args) 
      { 
        Console.WriteLine("Welcome to xTables"); 
     Console.WriteLine("In this application, you'll have to answer questions from"); 
     Console.WriteLine("the times table up to 12"); 
     Console.WriteLine("Good Luck!"); 
     //Question 1 
     Console.WriteLine("What is 1 x 6"); 
     string userAnswer = Console.ReadLine(); 


     if (userAnswer == "6") 
     { 
      string message = "Correct"; 
      Console.WriteLine(message); 
     } 

     else 
     { 
      string message = "Incorrect"; 
      Console.WriteLine(message); 
     } 



     //Question 2 
     Console.WriteLine("What is 2 x 3"); 
     Console.ReadLine(); 

     if (userAnswer == "6") 
     { 
      string message = "Correct"; 
      Console.WriteLine(message); 
     } 

     else 
     { 
      string message = "Incorrect"; 
      Console.WriteLine(message); 
     } 



     //Question 3 
     Console.WriteLine("What is 8 x 9"); 
     Console.ReadLine(); 

     if (userAnswer == "72") 
     { 
      string message = "Correct"; 
      Console.WriteLine(message); 
     } 

     else 
     { 
      string message = "Incorrect"; 
      Console.WriteLine(message); 
     } 


     //Question 4 
     Console.WriteLine("What is 5 x 6"); 
     Console.ReadLine(); 

     if (userAnswer == "30") 
     { 
      string message = "Correct"; 
      Console.WriteLine(message); 
     } 

     else 
     { 
      string message = "Incorrect"; 
      Console.WriteLine(message); 
     } 

     //Question 5 
     Console.WriteLine("What is 4 x 6"); 
     Console.ReadLine(); 

     if (userAnswer == "24") 
     { 
      string message = "Correct"; 
      Console.WriteLine(message); 
     } 

     else 
     { 
      string message = "Incorrect"; 
      Console.WriteLine(message); 
     } 


    } 
} 

}

ответ

1

В последних трех вам нужно сделать:

userAnswer = Console.ReadLine(); 

Вместо всего Console.ReadLine();

+0

Visual Studio говорит, что «userAnswer» уже определен в этой области. –

+0

@AdrianSimon. Вы случайно поставили «string userAnswer = Console.ReadLine()» вместо «userAnswer = Console.ReadLine()»? Первый попытается переопределить переменную, которая вызовет ошибку, о которой вы говорите. –

3

Во всех, кроме первого вопроса, то есть это:

Console.ReadLine(); 

Когда вы, вероятно, хотите, чтобы это:

userAnswer = Console.ReadLine(); 

EDIT для дальнейшего объяснения

Поскольку ответ на второй вопрос такой же, как и ответ на первый, может показаться, что он работает. (Вы можете вводить один и тот же ответ дважды.) Но на самом деле это не только последние три вопроса, которые не работают; только первый вопрос на самом деле делает то, что вы хотите.

-1

Я думаю, вы должны использовать следующее:

if (userAnswer.Equals(6)){ 
// Rest of the code 

} 
+0

Это сравнение ссылочного типа ('string') для типа значения (' int') и всегда будет возвращать 'false'. Вам нужно либо преобразовать 'int' в' string', либо наоборот. – Cameron

0

помимо вышеуказанных ответов, которые вы действительно не нужно использовать метод абстракции для переменной сообщения.

Console.WriteLine("Correct") 

будет работать так же хорошо

0

Вы должны использовать возвращаемое значение Console.ReadLine().

userAnswer = Console.ReadLine(); 

Как примечание стороны, это отличный кандидат для метода:

HandleQuestion(1, 6); 
HandleQuestion(2, 3); 
HandleQuestion(8, 9); 
HandleQuestion(5, 6); 
HandleQuestion(4, 6); 

void HandleQuestion(int operand1, int operand2) 
{ 
    Console.WriteLine("What is {0} x {1}", operand1, operand2); 
    string userAnswer = Console.ReadLine(); 

    if (userAnswer == (operand1 * operand2).ToString()) 
     Console.WriteLine("Correct"); 
    else 
     Console.WriteLine("Incorrect"); 

}

После того, как вы сделали это, вы можете перейти к генерации вопросов со случайными значениями операнды.

0

Вы не возвращаете readline() в переменную. Угадайте, что вы хотите сделать: userAnswer = Console.ReadLine();

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