c# - 如何在同一行中编写两个方法
问题描述
我有 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);
}
}
`
解决方案
现在,对于所有列表,您循环 3 次。然后你调用Console.WriteLine
which 在你的输出末尾添加一个换行符,所以它显示在下一行。
您想要做的是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});
然后,您可以循环该列表并显示输出。
推荐阅读
- java - 当数据不为空时,Firebase 中的 NullPointerException
- java - TomCat Servlet 执行 java.lang.StackOverflowError 异常
- html - 在 Woocommerce 中更改销售价格旁边的动态全价颜色
- ruby-on-rails - 通过 Rollify gem 查询角色时如何找到用户特定的角色记录
- vba - VBA Selenium 需要调用 chrome 扩展进行验证
- javascript - 速率限制整个 forEach 迭代中的内容量
- python - 使用 .loc 基于多索引计算更新多索引数据帧中的值
- webpack - Webpack 导入顺序在文件中的代码和文件夹中的代码之间创建阴影
- javascript - 如何使用哈希表来计算对象的出现次数?
- javascript - 如何防止侧边栏在页面加载时显示瞬间?