【发布时间】:2013-10-19 19:49:36
【问题描述】:
每次我尝试这样做时都会遇到一堵砖墙。我无法弄清楚为什么我的代码不会从文本文件中提取我的信息并对其进行排序。我所做的一切看起来都很好。 我在第 76、86 和 103 行收到 3 个错误。它们声明“yourChoicesItems”在当前上下文中不存在,并且 yourChoicesPrices' 在当前上下文中不存在。 但我看不出有什么问题。 当我输入日期时,例如: public string[] yourChoicesItems = {etc....} 它可以工作。 为什么这不起作用?
我的文本文件是:(每行前有一个空格)
蓝莓百吉饼 0.75
哈希布朗 2.50
瓶装苏打水 1.50
咖啡 0.90
甜甜圈 1.50
炸薯条 1.50
蓝莓松饼 0.85
LiteYogurt 0.75
热巧克力 1.75
洋葱汤 3.00
山核桃派 2.75
PurpleYam 2.75
草莓百吉饼 0.80
吐司 2.00
香草冰淇淋 2.75
冰茶 1.00
using System.IO;
namespace testce
{
public partial class MainScreen : Form
{
static void InsertSort(IComparable[] array)
{
int i, j;
for (i = 1; i < array.Length; i++)
{
IComparable value = array[i];
j = i - 1;
while ((j >= 0) && (array[j].CompareTo(value) > 0))
{
array[j + 1] = array[j];
j--;
}
array[j + 1] = value;
}
}
int count = 0;
double totalTax = 0;
double totalSale = 0;
public MainScreen()
{
FileStream fStream = new FileStream("menu.txt", FileMode.Open, FileAccess.Read);
StreamReader inFile = new StreamReader(fStream);
string inValue;
string[] values;
double price;
List<string> lines = new List<string>();
while (!inFile.EndOfStream)
{
inValue = inFile.ReadLine();
lines.Add(inValue);
values = (inValue.Split(" ".ToCharArray()));
price = double.Parse(values[2]);
InsertSort(values);
}
inFile.Close();
InitializeComponent();
InitializeControls();
for (int index = 0; index < listBox.SelectedIndices.Count; index++)
{
subTotal = subTotal + yourChoicesPrices[listBox.SelectedIndices[index]];
}
for (int index = 0; index < listBox.SelectedIndices.Count; index++)
{
textBox.AppendText(yourChoicesItems[listBox.SelectedIndices[index]] + "\n");
}
Text = "Thank you for using Food Systems Inc.";
this.listBox.DataSource = yourChoicesItems;
this.btnOne.Text = "Place Order";
this.label.Text = "Menu Selection";
this.labell.Text = "Order Information";
}
public System.Windows.Forms.ListBox listBox;
private System.Windows.Forms.Label label;
private System.Windows.Forms.Button btnOne;
private System.Windows.Forms.TextBox textBox;
}
}
【问题讨论】:
-
作为一般准则,对于给定的问题,这是太多的代码。尽量保持可读性。
-
不要重新发明轮子...对数组进行排序是一个已解决的问题,在 .NET 中有很多方法可以做到这一点,而无需自己编写排序算法。例如,您可以只使用
Array.Sort。 -
@ThomasLevesque - 这具有学习练习的所有特征,通常是关于重新发明一些东西。
-
我看不到你在哪里声明你的
YourChoicesItems和YourChoicesPrices -
string[] yourChoicesItems;和double[] yourChoicesPrices;虽然我可能会改用十进制
标签: c#