2013-10-13 20 views
-2

我想從Main()方法內部調用一個GetInputstring方法的值,然後繼續下一步。 我被卡在問候如何可以得到價值myInt和移動。從Main()函數內的方法調用值

myInt(其中它有兩個* around)在Main()中是它獲取錯誤的地方。

static void Main(string[] args) 
    { 

     GetInputstring(**myInt**); 

     if (**myInt** <= 0) 
     { 
      Write1(**myInt**); 
     } 
     else 
     { 
      Write2(**myInt**); 
     } 
     Console.ReadKey(); 
    } 

    public int GetInputstring(int myInt) 
    { 
     string myInput; 
     //int myInt; 

     Console.Write("Please enter a number: "); 
     myInput = Console.ReadLine(); 

     myInt = Int32.Parse(myInput); 
     return myInt;    
    } 

    static void Write1(int myInt) 
    { 
     while (myInt <= 0) 
     { 
      Console.WriteLine("{0}", myInt++); 
     } 
    } 

    static void Write2(int myInt) 
    { 
     while (myInt >= 0) 
     { 
      Console.WriteLine("{0}", myInt--); 
     } 
    } 
+0

MyInt是您的參數(您傳遞給您的方法的值)並且未初始化。此外,你不趕上你的返回值(這應該是myInt) –

+0

http://csharp-station.com/Tutorial/CSharp/ –

回答

0

是參數,它不是初始化(你傳遞給你的方法的值)。進一步你不趕上你的返回值(這應該是myInt)

你還需要使你的方法是靜態的,以便從靜態方法調用它們,或者你創建一個類的實例並調用它的方法

那就是你如何得到你想要的東西:

static void Main(string[] args) 
{ 

    int myInt = GetInputstring(); //MyInt gets set with your return value 

    if (myInt <= 0) 
    { 
     Write1(myInt); 
    } 
    else 
    { 
     Write2(myInt); 
    } 
    Console.ReadKey(); 
} 

public static int GetInputstring() //Deleted parameter because you don't need it. 
{ 
    string myInput; 
    //int myInt; 

    Console.Write("Please enter a number: "); 
    myInput = Console.ReadLine(); 

    int myInt = Int32.Parse(myInput); 
    return myInt;    
} 
+0

我得到GetInputstring()錯誤; 「非靜態字段或屬性需要對象引用」。此外,在GetInputstring()方法中,在myInt上獲取兩個錯誤:「名稱'myInt'在當前上下文中不存在。 – Kudohs

+1

您是否已將您的方法static?檢查我的編輯,忘了創建一個整數:'int myInt = Int32.Parse(myInput);'或者你可以返回值,只是當它與'返回Int32.Parse(myInput);' –

+0

解析謝謝。 。它運作良好。 – Kudohs

0

需要初始化你myInt變量並將其存儲在本地或全局範圍。有了這個變量,你將需要使用從GetInputString()得到的值來設置它,因爲你沒有將int作爲ref傳遞,它將不會在方法中分配。你也需要讓你的方法靜態的,所以他們可以從Main被稱爲沒有創建一個實例,例如:public static int GetInputstring()

int myInt = 0; 
myInt = GetInputstring(myInt); 

if (myInt <= 0) 
{ 
    Write1(myInt); 
} 
else 
{ 
    Write2(myInt); 
} 
Console.ReadKey(); 

或者(最好),你可以做GetInputString()分配值,因爲它需要這麼想的myInt作爲參數傳遞。

static void Main(string[] args) 
{ 
    int myInt = GetInputstring(); 

    if (myInt <= 0) 
    { 
     Write1(myInt); 
    } 
    else 
    { 
     Write2(myInt); 
    } 
    Console.ReadKey(); 
} 

public static int GetInputstring() 
{ 
    Console.Write("Please enter a number: "); 
    string myInput = Console.ReadLine(); 
    return Int32.Parse(myInput);    
}