2017-02-20 75 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();

相关问题