简体   繁体   中英

I don't understand 'new string' and the [i] over here

So i don't understand the 'new string' over here. I've tried reading up on it but i couldn't find any concrete answers that are simple to understand. what's the difference between string and new string?

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

      Console.Write("\nInput number of students: ");
      var totalstudents = int.Parse(Console.ReadLine());

        var name = new string [totalstudents];
        var grade = new int [totalstudents]; 

My program won't compile became of unexpected symbol 'name' and 'grade' which i think may be connected to [i] which i also don't understand.

  for (int i =0 ; i<totalstudents ; i++)
        {
         Console.WriteLine("\nInput student name: ")
          name[i] = Console.ReadLine(); 
         Console.WriteLine("\nInput student grade: ")
          grade[i] = int.parse(Console.ReadLine());
        }

  foreach(var gradesof in grade)
   { 
    Console.WriteLine(gradesof);
   }

  }
}

}

string is a string. string[] is an array of strings, ie an object consisting of indexable string elements.

string s = "hello"; // Declares and initializes a string.

string[] a = new string[3]; // Declares and initializes a string array of length 3.
                            // Every element of the array is `null` so far.

// Fill the array with meaningful values.
a[0] = "hello";
a[1] = "world";
a[2] = "!";

You can also use an array intializer to get the same result:

string[] a = new string[] { "hello", "world", "!" };

You can retrieve a single element like this:

string world = a[1];

Loop through an array with for :

for (int i = 0; i < a.Length; i++) {
    Console.WriteLine($"a[{i}] = \"{a[i]}\"");
}

An array can be of any type, like the grade array in your example being of type int[] .

See: Arrays (C# Programming Guide)

As mentioned in the comments, the new string[...] is creating an array.

Your compile problems include...

The lines:

Console.WriteLine("\nInput student name: ")
Console.WriteLine("\nInput student grade: ")

…are both missing a semicolon ; at the end

Also:

grade[i] = int.parse(Console.ReadLine());

…parse should be Parse .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM