首页 > 解决方案 > 如何在同一行中编写两个方法

问题描述

我有 3 个数组。一个用于项目编号,一个用于项目描述,一个用于价格。

我希望能够从中创建一个“表”,因此它的内容如下:

Item Number:    Description:    Price:
   50              Water          $50
   752             Carrots        $.60
   67              Ice             $9 

等等。我尝试使用 foreach 语句创建方法,然后调用这些方法。它可以工作,但不能并排打印。有想法该怎么解决这个吗?

这是代码`

using static System.Console;
class FoodOrder
{
         static void Main()
        {
        //Variables used in the method
        const int MENU_ASTERIKS = 42;
        string description = "Description", itemNumber = "Item number", price = "Price";
        string[] itemDescription = { "Cheese Frise", "Corn Dogs", "Cheeseburger", "Hamburger", "Fries", "Fountain Drink", "Philly Cheese Steak", "Tacos" };
        int[] itemNumList = { 20, 23, 25, 31, 35, 38, 39, 34, };
        double[] itemPrice = { 2.95, 1.95, 2.25, 3.10, 4.50, 3.65, 5.00, 2.75};
        Write("\t");
        for (int x = 0; x < MENU_ASTERIKS; ++x) //Creates a top border for the menu with the prices and is the start of the menu 
            Write("*");
        WriteLine(" ");
        Write("\t   {0}\t{1}\t{2}", itemNumber, description, price);
        DisplayItemNum(itemNumList); DisplayDescriptions(itemDescription);
    }
        //Method to dispay item number
        private static void DisplayItemNum( params int[] itemNums)
        {
        WriteLine("\n");
        foreach (int number in itemNums)
            WriteLine("\t        {0} ", number);
        }
        //Method to Display item Number
        private static void DisplayDescriptions(params string[] desc)
        {
        WriteLine("\n");
        foreach (string objects in desc)
            WriteLine("\t\t\t{0}", objects);


        }

}

`

源代码

源文件的输出

标签: c#arraysmethods

解决方案


现在,对于所有列表,您循环 3 次。然后你调用Console.WriteLinewhich 在你的输出末尾添加一个换行符,所以它显示在下一行。

您想要做的是Console.Write不添加换行符的调用。还有更好的方法可以做到这一点。除了保留 3 个单独的列表,您还可以将您的信息捆绑在一个类中并创建一个列表:

public class MyTableRow
{
   public int Number {get;set;}
   public string Description {get;set;}
   public float Price {get;set;}
}

.Add()然后你可以创建这个类的一个新对象,用你的数据和你的列表填充它Main,例如var MyTableRows = new List<MyTableRow>();然后MyTableRows.Add(new TableRow{ Number = 1, Description = "REE", Price = 1.0f});

然后,您可以循环该列表并显示输出。


推荐阅读