【问题标题】:How Do I Write Two Methods In The Same Line [duplicate]如何在同一行中编写两个方法[重复]
【发布时间】:2020-07-24 05:06:59
【问题描述】:

我有 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);


        }

}

`

【问题讨论】:

  • 请输入您的代码而不是图像。会更容易阅读
  • @D.J.我试过了,但这只是将数组中的对象写在同一行

标签: c# arrays methods


【解决方案1】:

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

您想要做的是调用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&lt;MyTableRow&gt;(); 然后MyTableRows.Add(new TableRow{ Number = 1, Description = "REE", Price = 1.0f});

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

【讨论】:

  • @Sommment 哦,好吧,所以我对 c# 真的很陌生,刚刚接触了我课堂上的方法,所以我有点理解这一点,所以我要尝试一下。如果你有时间,你能写出每个动作的简短描述吗?这样我可以更好地学习它而不是复制和粘贴变量?
  • @SpacedOutKID 嗨,这些确实是一般编程的基础知识,所以我建议您查看一些教程。还要在线阅读 c# 语言的所有功能docs.microsoft.com/en-us/dotnet/csharp/getting-started/… 不要试图一次理解所有内容,它不会起作用。首先阅读所有内容,在您的脑海中进行概述,然后大致了解您在做什么,然后将这些点点滴滴放在一起谷歌搜索。我就是这样学习的,并且仍然以专业开发人员的身份学习。
  • 专业,因为我在专业能力中使用编程,而不像我在任何方面都是专业人士;)
猜你喜欢
  • 1970-01-01
  • 2013-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-02
  • 1970-01-01
  • 2014-06-22
  • 1970-01-01
相关资源
最近更新 更多