2014-03-06 37 views
1

嗨我寫了一個代碼,假設顯示每個人的名字,然後能夠選擇我選擇哪個人,然後顯示他們的成績,讓我能夠改變它。我得到它顯示他們的成績,但我不知道如何改變這個人的成績價值,而是改變每個人的成績,並顯示它,我該如何改變它?所以它只顯示那個人的變化?並添加我想要的任何價值?我如何在人名旁邊顯示更改的值?如果你能幫助我,我會非常感謝你。更改數組中的值和顯示

static void Main(string[] args) 
    { 
     int selection; 
     do 
     { 
      String[] A = { "Tim", "Jhon", "Sam", "Derp"}; 
      int[] B = { 90, 89, 60, 40 }; 
      DisplayMenu(); 
      Console.Write("Enter you selection: "); 
      int.TryParse(Console.ReadLine(),out selection); 
      switch (selection) 
      { 
       case 1: 
        Console.WriteLine(
      "{0} ", B[0]); 
        AddToGrade(B); 
        break; 
       case 2: 
        Console.WriteLine(
      "{0} ", B[1]); 
        AddToGrade(B); 
        break; 
       case 3: 
        Console.WriteLine(
      "{0} ", B[2]); 
        AddToGrade(B); 
        break; 
       default: 
        Console.WriteLine(
      "{0} ", B[3]); 
        AddToGrade(B); 
        break; 
      } 
      Console.ReadKey(); 
     } while (selection != 4); 

    } 
    static void DisplayMenu() 
    { 
     Console.Clear(); 
     Console.WriteLine("Select a student 1-4"); 
     Console.WriteLine("1. Time"); 
     Console.WriteLine("2. Jhon"); 
     Console.WriteLine("3. Sam"); 
     Console.WriteLine("4. Derp"); 
    } 
    static void AddToGrade(int[] array) 
    { 

     Console.WriteLine("Input New Value: "); 
     int newValue = Convert.ToInt32(Console.ReadLine()); 
     for (int i = 0; i < array.Length; i++) 
     { 
      array[i] += newValue; 
      Console.Write("New Grade: {0}", array[i]); 
     } 
    } 
+1

由於C#是一種面向對象的語言,因此您應該考慮創建一個Person或Student類。 –

+0

我完全同意Mert,雖然我寫了一個答案,但你應該在修正你的代碼時考慮到這個評論。 – Ofiris

+0

@Ofiris我會感謝您的意見和幫助。 – TheBoringGuy

回答

0

AddToGrade應該接受index代表要改變的等級。

static void AddToGrade(int[] array ,int index) 
{ 
    Console.WriteLine("Input New Value: "); 
    int newValue = Convert.ToInt32(Console.ReadLine()); 
    array[index] += newValue; 
    Console.Write("New Grade: {0}", array[index]); 
} 

而且你的開關(Console.ReadKey();前)後,只需要調用此:

AddToGrade(B, selection - 1); 

此外,你應該使用更多的功能,使你的代碼強勁而優雅, 例如(這個例子也alliw你保留原來的格式在一個地方)

static void DisplayNameGrade(int index, String[] A, int[] B) 
{ 
    Console.WriteLine("Name: {0}, Grade: {1}", A[index], B[index]) 
} 

一般來說,你應該學習的Object Oriented Programming的基本概念,並用類,部件及功能設計你的代碼。

+0

嗯,我得到一個藍色的錯誤代碼在數組[i]它不存在於當前的上下文中。 – TheBoringGuy

+0

應該是'數組[索引]' – Ofiris

+0

我看到,並且在「A」[index]和B – TheBoringGuy