2017-10-16 58 views
1

我想知道如何将用户输入显示为编号列表?例如如何将输出显示为编号列表

  1. 果酱
  2. 东西
  3. 别的东西

这是我迄今为止在关于设置阵列和按字母顺序排序,但想也显示为每以上,无法在任何地方找到任何信息。提前致谢。

//call method to sort array in alphabetical order 
     fillArraySort(); 

     //call method to display in numbered list 
     //displayNumberedList(); 

    } 

    /*declare the array 
    ask user for index (size of array) and store user input array*/ 

    static void fillArraySort() 
    { 
     int a; 
     Console.WriteLine("How many inanimate object names do you wish to enter?"); 
     a = int.Parse(Console.ReadLine()); 
     int[] index = new int[a]; 
     for (int i = 0; i < index.Length; i++) 
     { 
      Console.WriteLine("Enter name of object:"); 
      index [i] = int.Parse(Console.ReadLine()); 
     } 
     Array.Sort(index); 
     Console.WriteLine("The array sorted in alphabetical order is: "); 
     foreach (var i in index) 
     { 
      Console.WriteLine(i); 

     } 
     Console.WriteLine(); 
     Console.ReadLine(); 
    } 


    //static void displayNumberedList() 
    //{ 
     //code 
+3

首先,我建议,如果要排序的名单,你使用'字符串'数组而不是'int'数组。 – Deolus

+0

你在代码中的所有内容都是一个你已经排序的int数组。您希望我们建议如何从用户处获取字符串输入? –

+0

嗨。感谢您的建议重新字符串数组@Deolus。我将它改为string而不是int。 – ChunLi

回答

0
static void FillArraySort() 
{ 
    Console.WriteLine("How many inanimate object names do you wish to enter?"); 

    int number = int.Parse(Console.ReadLine()); 

    var array = new string[number]; 

    for (int index = 0; index < number; index++) 
    { 
     var message = string.Format("Enter name of object {0}:", index + 1); 

     Console.WriteLine(message); 

     array[index] = Console.ReadLine(); 
    } 

    Array.Sort(array); 

    Console.WriteLine(); 
    Console.WriteLine("The array sorted in alphabetical order is:"); 

    for (int index = 0; index < number; index++) 
    { 
     var item = array[index]; 

     var message = string.Format("{0}. {1}", index + 1, item); 

     Console.WriteLine(message); 
    } 

    Console.WriteLine(); 
    Console.WriteLine("Press any key to exit..."); 
    Console.ReadLine(); 
} 
+0

谢谢,这看起来不错。我将通读并将其分解为多种方法。干杯:) – ChunLi

1

试试这个:

string[] items = new string[] 
{ 
    "Jam", "Tea", "Something", "Something else" 
}; 

Console.WriteLine(
    String.Join(
     Environment.NewLine, 
     items.Select((x, n) => $"{n + 1}. {x}"))); 

这给:

 
1. Jam 
2. Tea 
3. Something 
4. Something else