2015-01-26 47 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) { 
相關問題