2013-08-24 150 views
0

我想有一個人輸入的用戶獲取數據,在我的代碼長度和寬度的值,這裏是我走到這一步:從通過命令行

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

namespace ConsoleApplication2 
{ 
    class Rectangle 
    { 
     double length; 
     double width; 
     double a; 

     static double Main(string[] args) 
     { 
      length = Console.Read(); 
      width = Console.Read(); 
     } 

     public void Acceptdetails() 
     { 

     } 

     public double GetArea() 
     { 
      return length * width; 
     } 

     public void Display() 
     { 
      Console.WriteLine("Length: {0}", length); 
      Console.WriteLine("Width: {0}", width); 
      Console.WriteLine("Area: {0}", GetArea()); 
     } 
    } 

    class ExecuteRectangle 
    { 
     public void Main() 
     { 
      Rectangle r = new Rectangle(); 

      r.Display(); 
      Console.ReadLine(); 
     } 
    } 
} 

試圖用兩個Main方法解決這個問題的方法是錯誤的?這是我從http://www.tutorialspoint.com/csharp/csharp_basic_syntax.htm複製的代碼我試圖對其進行修改,以獲得有關此編程語言的更多經驗。

+0

'Console.Read'返回1 **字符**,不是整數(或雙倍)你期望的價值。閱讀一些關於'Console.ReadLine'的文檔,'double.Parse' – I4V

+0

與你的例子不同,這個類是靜態的,所以要創建長度,寬度等靜態變量。沒有理由有多個名爲main的方法。將main更改爲static int Main(string [] args),並在底部放置一個返回0。 – dcaswell

回答

0

在這種情況下,你將不得不告訴編譯,這是與入口點的類。

「如果您的編譯包含多個帶有Main方法的類型,則可以指定哪種類型包含要用作程序入口點的Main方法。」

http://msdn.microsoft.com/en-us/library/x3eht538.aspx

是的,有兩個主要的方法是混亂和毫無意義的。

+0

我已經指定了使用哪種Main方法。我仍然收到錯誤。 – novellof

+1

'ConsoleApplication2.Rectangle'沒有合適的靜態Main方法 – novellof

+0

哪個錯誤?輸出在哪裏? – Oscar

4

有一些問題,你的代碼,讓我們對它們進行分析:

  1. 程序必須有一個獨特的切入點,它必須是一個聲明爲靜態無效的,在這裏你有兩個主要的,但他們都錯了

  2. 你在你的靜態Main一個在矩形類,你不能引用變量長度e×寬度,因爲他們不聲明爲靜態

  3. console.Read()返回表示一個字符的int所以如果用戶輸入使用1,你可能在你的可變長度不同的值
  4. 您的靜態雙主不返回雙

我認爲,你想要的是:

  1. 聲明靜態雙主爲void main()
  2. 聲明你的void Main作爲靜態void Main(string [] args)
  3. 在你的新的靜態void Main調用中(創建矩形後)它是Main方法(這樣做你必須定義它作爲公衆)
  4. 使用輸入行,而不是閱讀()
  5. READLINE返回一個字符串,所以要變換在雙你必須使用lenght = double.Parse(到Console.ReadLine())
  6. 終於打電話給你r.display( )

這是一個可以做你想做的工作代碼。複製粘貼前 注意,因爲你想和李爾閱讀的步驟和嘗試修復它不看代碼

class Rectangle 
{ 
    double length; 
    double width; 
    double a; 
    public void GetValues() 
    { 
     length = double.Parse(Console.ReadLine()); 
     width = double.Parse(Console.ReadLine()); 
    } 
    public void Acceptdetails() 
    { 

    } 
    public double GetArea() 
    { 
     return length * width; 
    } 
    public void Display() 
    { 
     Console.WriteLine("Length: {0}", length); 
     Console.WriteLine("Width: {0}", width); 
     Console.WriteLine("Area: {0}", GetArea()); 
    } 

} 
class ExecuteRectangle 
{ 
    public static void Main(string[] args) 
    { 

     Rectangle r = new Rectangle(); 
     r.GetValues(); 
     r.Display(); 
     Console.ReadLine(); 
    } 
} 
+0

看看我的代碼我將Main重命名爲更合適的名稱(GetValues)。你的程序必須有一個定義爲public static void Main(string [] args)的入口點,入口點是程序在執行時調用的第一個方法。 –

+0

謝謝,我會像牧師那樣對聖經進行研究。 – novellof