2017-02-20 37 views
-1

我是新來的C#,我不明白爲什麼這不起作用。我得到錯誤是主題()主要如下所述。如何調用C#中的主要字符串數組方法#

我的代碼如下:

class Program 
    { 
     static void Main(string[] args) 
     {string sub; 
      // string brd; 
      brd = board(); 
      sub = subjects(); // Error 
      //Console.WriteLine(brd); 
      Console.WriteLine(sub); 
      Console.ReadLine(); 
     } 
     public static string[] subjects() 
     { 
     Console.WriteLine("Please Enter How many Subject Do you Want to input"); 
     int limit = System.Convert.ToInt32(Console.ReadLine()); 
      string[] Subjects = new string[limit]; 
      int[] index = new int[limit]; 
      for (limit = 0; limit <= index.Length; limit++) 
      { 
       Console.WriteLine("Please Enter Subject Name " + limit + 1); 
       Subjects[limit] = Console.ReadLine(); 
      } 
      return Subjects; 
     } 
    } 
+0

你得到了什麼錯誤? – kritikaTalwar

+0

當發佈一個問題時,您應該格式化您的代碼以便於閱讀(尊重C#約定),您應該以明確的方式向編譯器提供確切的錯誤消息,並且您應該將其指向代碼中。 –

回答

1

請參閱/ ** /註釋

class Program 
{ 
    static void Main(string[] args) 
    { 
     string sub; /*1. Remove this line*/ 
     // string brd; 
     brd = board(); 
     sub = subjects(); /*2. string[] sub = subjects();*/ 
     //Console.WriteLine(brd); 
     Console.WriteLine(sub); 
     Console.ReadLine(); 
    } 
    public static string[] subjects() 
    { 
     Console.WriteLine("Please Enter How many Subject Do you Want to input"); 
     int limit = System.Convert.ToInt32(Console.ReadLine()); 
     string[] Subjects = new string[limit]; 
     int[] index = new int[limit]; /*3. Remove this line -> Redundant*/ 
     /*4. Change variable `limit` to `i`*/ 
     for (int i = 0; i <= limit; i++) 
     { 
      Console.WriteLine("Please Enter Subject Name " + i + 1); 
      Subjects[i] = Console.ReadLine(); 
     } 
     return Subjects; 
    } 
} 
+0

希望這是一個不錯的回答方法,在代碼中添加正確答案並給出解釋。你的代碼仍然會顯示問題中提到的錯誤。 –

3

試試這個:

string[] sub = subjects(); 

取而代之的是:

string sub; 
sub = subjects(); 

因爲你得到數組的字符串,並將其傳遞給正常的字符串。

1

您正在將sub定義爲字符串(string sub),但方法subjects is returning a string array. So sub is not able to hold the return value from that method. you have to change the return type of sub from string to string []`。這意味着該聲明應該是這樣的:

string[] sub = subjects(); 

還是以更簡單的方法,你可以把它像這樣:

var sub = subjects(); 

因此,編譯器會自動選擇基於從返回值的返回類型該方法。如果你對這種賦值中的數據類型感到困惑,你可以讓編譯器根據這些值決定數據類型。

0

現在有沒有代碼,但運行時的任何錯誤的錯誤編譯器不打印(子)
Console.WriteLine(分); Console.ReadLine();

相關問題