2015-01-26 43 views
1

我认为这个错误与If语句有关,但是我试过寻找错误,而且大部分问题都是由语法错误引起的,这对我来说似乎不是这样。预先感谢您的帮助。为什么显示无效的表达式项“字符串”?

using System; 

namespace FirstConsoleProjectSolution 
{ 

    class MainClass 
    { 

    public static void Main (string[] args) // this is a method called "Main". It is called when the program starts. 
    { 
     string square; 
     string cylinder; 

     Console.WriteLine ("Please enter a shape"); 

     if (string == square) { 

      double length; 
      double width; 
      double height; 

      Console.WriteLine ("Please enter length"); 
      Console.ReadLine (Convert.ToDouble()); 

      Console.WriteLine ("Please enter width"); 
      Console.ReadLine (Convert.ToDouble()); 

      Console.WriteLine ("Please enter height"); 
      Console.ReadLine (Convert.ToDouble()); 

      Console.WriteLine ("Your total volume is" + length * width * height); 
     } 

     if (string == cylinder) { 

      double areaOfBase; 
      double height; 

      Console.WriteLine ("Please enter area of base"); 
      Console.ReadLine (Convert.ToDouble()); 

      Console.WriteLine ("Please enter height"); 
      Console.ReadLine (Convert.ToDouble()); 

      Console.WriteLine ("Your total volume is" + areaOfBase * height); 

     } 
    } 

    } 

} 

回答

3

这是因为这句话的:

if (string == square) { 

string关键字表示数据类型,这是不可能的比较数据类型和一个字符串。

您打印出来的信息表明您正在尝试输入内容,但没有输入。我认为你正在尝试做的是这样的:

Console.WriteLine ("Please enter a shape"); 
string shape = Console.ReadLine(); 
if (shape == "square") { 
    ... 

后来的代码,当您尝试输入数字,你可以使用这样的代码来解析字符串,并把它放在一个变量:

length = Convert.ToDouble(Console.ReadLine()); 
+0

谢谢你这么多你得到的错误! – 2015-01-26 21:03:04

0

您没有变数string。使用string也是非法的,因为它是该语言的关键字。

如果您对使用变量名称string(我可能会避免它,因为在这种情况下它不是很具描述性)的内容,您可以通过将@符号添加到变量名的开头来转义关键字。

您的代码有多个问题。首先是你实际上并没有在开始时要求任何输入。如果你的意图是从用户那里获得输入,你应该考虑将Console.ReadLine()的值赋给一个变量。你应该考虑的东西,如:

Console.WriteLine("Please enter a shape"); 
string shapeType = Console.ReadLine(); 

if (shape == "square") 
{ 
    //do something 
} 

如果你坚持命名您的变量string,你将不得不说

string @string = Console.ReadLine();

+1

谢谢!没有意识到声明变量并不意味着声明他们的数据类型,而是发明了一个“名称”。 – 2015-01-26 21:04:38

0

你还没有指定的字符串变量

 string square; 
     string cylinder; 

您还没有捕获到用户的输入

解决方案

string square = "square"; 
string cylinder = "cylinder"; 
string input; 

Console.WriteLine ("Please enter a shape"); 
input = Console.ReadLine(); 

if (input == square) { 

    // Do stuff 

} 

,因为你是比较原始的类型声明“串”到字符串类型缸的实例

if (string == square) { 
相关问题