2013-03-25 20 views
1

我已指示寫收集保齡球得分(整數),並且從用戶的名稱,用空格隔開的程序,以及使用它們中的每排序成陣列Split方法。輸出必須被格式化找到的平均分數,並將其輸出到控制檯,以及排序成績(和名稱)在最低以最高的。使用數組拆分法分離的名字/號碼

我已經能夠做到,除了找到一個方法來與它們對應的分數排序的名稱一切。

這是我到目前爲止。爲了澄清,我需要幫助爲我的數組名稱編寫排序算法。

using System; 

class Program 
{ 
    //class variables 
    const int MAX = 10; 

    static void Main() 
    { 
     //declare array 
     int[] score = new int[MAX]; 
     string[] name = new string[MAX]; 

     //program prologue 
     Console.WriteLine("****************Bowling Project****************"); 
     Console.WriteLine("Please enter a name and a score for each player. For example 'John 145'.\nHit enter when you are done."); 

     //for loop to get input 
     for (int i=0; i<MAX; i++) 
     { 
      Console.Write("Enter a name and a score for player #{0}: ", (i + 1)); 
      string input = Console.ReadLine(); 
      if (input == "") 
      { 

       break; // if nothing is entered, it will break the loop 
      } 
      //split the user data into 2 arrays (integer and string) 
      string[] separateInput = input.Split(); 
      name[i] = separateInput[0]; 
      score[i] = int.Parse(separateInput[1]); 
     } 

     Console.WriteLine("\n****************Input Complete****************"); 

     //calculate the average score and send to the console 
     CalculateScores(score); 

     Console.WriteLine("The scores for the game are:"); 

     //sort the scores 
     BubbleSort(score); 


     Console.ReadLine(); 
    }//End Main() 
    //CalculateScores Method 
    //Calculates the average score of an array of integers 
    //Takes an array of integers as parameters 
    //Returns void 
    //Outputs the average to the console 
    static void CalculateScores(int[] score) 
    { 
     int sum = 0; 
     int average = 0; 
     for (int i = 0; i < score.Length; i++) 
     { 
      sum += score[i]; 
      average = sum/score.Length; 
     } 
     Console.WriteLine("The average score was {0}", average); 
    }//End calculateScores 

    //Swap method 
    //Takes 2 integers as parameters 
    //Switches the value of 2 integers (a and b) 
    static void Swap(ref int a, ref int b) 
    { 
     int temp = a; 
     a = b; 
     b = temp; 
    } 

    //BubbleSort method 
    //Sorts an array of integers 
    //Takes an array of integers as a parameter 
    //Returns void 
    //Outputs to the console 
    static void BubbleSort(int[] score) 
    { 

     for (int j = 0; j < score.Length -1; j++) 
     { 
      for (int i = 0; i < score.Length - 1; i++) 
      { 
       if (score[i] > score[i + 1]) 
       { 
        Swap(ref score[i], ref score[i + 1]); 
       } 
      } 
     } 
     foreach (int a in score) 
      Console.WriteLine("{0}", a); 
     Console.ReadLine(); 
    } 
}//End class Program 
+0

請花些時間來正確設置代碼的格式,並且它是作業的事實與被問的問題沒有關係。快速瀏覽一下 – 2013-03-25 16:10:51

+0

:使用2個數組有點奇怪。但無論如何。如果你爲一個數組排序,你爲什麼不交換相同的數組位置給玩家,以便玩家和得分的相應位置是相同的?所以不是({Swap(ref score [i],ref score [i + 1]);})({Swap(ref score [i],ref score [i + 1]); Swap(ref player [i] ,ref player [i + 1]);}) – Offler 2013-03-25 16:15:29

+0

對不起,這是我第一次在這裏問了一年多的問題。我甚至沒有意識到它的格式不正確?哪部分不正確?謝謝 – xavi 2013-03-25 16:16:17

回答

1

你應該製作一個單獨的類,用它的分數數組存儲玩家。

然後讓玩家,你可以進行排序基於其name

編輯陣列:我已經更新了我的答案是一個實現播放器類是建立在你的原代碼。如果這是一個大學項目,這可能會被抄襲檢查者看到,所以我會謹慎使用它。

public class Player 
{ 
    public Player(){} 
    public Player(string name, int score) 
    { 
     m_name = name; 
     m_score = score; 
    } 
    public Player(Player p) 
    { 
     m_name = p.Name; 
     m_score = p.Score; 
    } 
    public string Name 
    { 
     get{return m_name;} 
    } 
    public int Score 
    { 
     get{return m_score;} 
    } 
    private string m_name 
    private int m_score 
} 

Player[] players = new Player[MAX]; 
static void BubbleSort(Player[] players) 
{ 

    for (int j = 0; j < players.Length -1; j++) 
    { 
     for (int i = 0; i < players.Length - 1; i++) 
     { 
      if (players[i].Score > players[i + 1].Score) 
      { 
       Swap(ref players[i], ref players[i + 1]); 
      } 
     } 
    } 
    foreach (Player a in players) 
     Console.WriteLine("{0}", a.Score); 
    Console.ReadLine(); 
} 
    static void Swap(ref Player a, ref Player b) 
    { 
     Player temp = a; 
     a = b; 
     b = temp; 
    } 
+0

謝謝你的幫助!我曾考慮過這樣做,但如果我不使用.split方法,我會得到點數。 – xavi 2013-03-25 16:17:55

+0

@xavi - 你仍然可以使用拆分方法嗎?當我讀到它時,聽起來像是在閱讀諸如「name 1 2 3」之類的字符串,所以你用splitstring [0]實例化一個新的玩家名稱,然後其餘的分數爲 – Sayse 2013-03-25 16:21:42

+0

@xavi - 一些練習,我會去寫一個關於如何用sam的建議來使用玩家類的例子。我不會將它包含在你的任務中,因爲你可能會被拖延。但認爲你會發現它有趣的未來:) – Sayse 2013-03-25 16:57:59

2

假設names[]相當於用1至1 score[]

只要把你的BubbleSort方法,並同時通過names[]score[]進去

然後,當你在score[]再做一次手術做它也在names[]

像這樣

static void BubbleSort(int[] score, string[] names) 
{ 

    for (int j = 0; j < score.Length -1; j++) 
    { 
     for (int i = 0; i < score.Length - 1; i++) 
     { 
      if (score[i] > score[i + 1]) 
      { 
       Swap(ref score[i], ref score[i + 1]); 
       Swap(ref names[i], ref names[i + 1]); 
      } 
     } 
    } 
    foreach (int a in score) 
     Console.WriteLine("{0}", a); 
    Console.ReadLine(); 
} 

你可能必須做出字符串

static void Swap(ref string a, ref string b) 
{ 
    string temp = a; 
    a = b; 
    b = temp; 
} 
+0

感謝您的輸入!我其實已經嘗試過了,但我的bubblesort方法只適用於整數。我試着用names []代替scores []並用string []代替int []來重寫它,但它不會編譯。 – xavi 2013-03-25 16:14:59

+0

@xavi我編輯了我的帖子,以澄清我的意圖是什麼 – 2013-03-25 16:17:28

+0

我會試試這個。 – xavi 2013-03-25 16:20:43

0

而不是使用鬆散關聯值的兩個集合的swap方法,使用類的一個集合:

public class BowlingScore { 

    public string Name { get; private set; } 
    public int Score { get; private set; } 

    public BowlingScore(string name, int score) { 
    Name = name; 
    Score = score; 
    } 

} 

使用列表,而不是共同的數組llection:

List<BowlingScore> scores = new List<BowlingScore>(); 

在你的循環中,您可以創建類的實例,並添加到列表:

BowlingScore item = new BowlingScore(separateInput[0], int.Parse(separateInput[1]); 
scores.Add(item); 

通過使用一個列表,而不是一個數組的,它只會包含的項目,你實際上加。您當前的代碼就需要另一個變量保持數組中的許多項目是如何實際使用的軌道,讓您不包括在結束空的人。

現在,有您的名字和分數作爲一個單元,您可以使用同樣的方法,因爲你用於排序數組列表進行排序,只有你比較對象的屬性。當您交換整個對象時,名稱將按照得分進行排序,反之亦然。

列表中的項目可以像使用數組一樣使用索引來訪問,只有列表的長度位於Count屬性中,而不是Length

+0

看起來與我的回答非常相似... – Sayse 2013-03-25 16:32:37

0

不需要創建兩個數組,因爲你失去了玩家名字和分數之間的語義含義。但也沒有必要爲此創建一個新類。您可以重新使用Tuple < ...>或KeyValuePair < ...>內置的類/結構。爲了排序,你可以使用linq-extension方法。

static void Main(string[] args) 
{ 
    // just some sample players 
    const string player1 = "David 100"; 
    const string player2 = "Jennifer 1430"; 
    const string player3 = "Eve 234"; 

    // the string-array with information about players 
    var players = new[] { player1, player2, player3 }; 

    // initialize the array: a tuple is the name of the player and the score 
    var scores = new List<Tuple<string, int>>(players.Length); 

    foreach (string player in players) 
    { 
     // split by whitespace 
     string[] info = player.Split(' '); 

     // be failure tolerant: split must result in at least 2 entries and second one must be integer 
     int score; 
     if (info.Length <= 2 && int.TryParse(info[1], out score)) 
      scores.Add(new Tuple<string, int>(info[0], score)); 
    } 

    // print average score 
    Console.WriteLine("Average score for {0} players is: {1}{2}", scores.Count, scores.Select(t => t.Item2).Average(), Environment.NewLine); 

    // print score of each single player (ordered from highest to lowest score) 
    foreach (Tuple<string, int> score in scores.OrderByDescending(t=>t.Item2)) 
     Console.WriteLine("Player '{0}' => score: {1}", score.Item1, score.Item2); 

    Console.WriteLine(); 
    Console.WriteLine("Press any key to exit."); 
    Console.ReadKey(); 
}