【问题标题】:Trying to use text from a file and sort it尝试使用文件中的文本并对其进行排序
【发布时间】: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 - 这具有学习练习的所有特征,通常是关于重新发明一些东西。
  • 我看不到你在哪里声明你的 YourChoicesItemsYourChoicesPrices
  • string[] yourChoicesItems;double[] yourChoicesPrices; 虽然我可能会改用十进制

标签: c#


【解决方案1】:

您的代码类似于 Java,在 c# 中不太正确,所以我做了一些修改:

class FoodData
{
    public string FoodName { get; set; }
    public double Price { get; set; }
}

首先,我们使用的是 oop 语言,因此最好使用具有两个属性的类而不是单个 String

if (!System.IO.File.Exists("menu.txt"))
            return;
        string[] values;
        double price;
        List<FoodData> lines = new List<FoodData>();
        using (System.IO.StreamReader sr = new System.IO.StreamReader("menu.txt"))
        {
            while (sr.Peek() > -1)
            {
                values = sr.ReadLine().Split(' ');
                FoodData tmp = new FoodData();
                tmp.FoodName = values[0];
                tmp.Price = Convert.ToDouble(values[1]);
                lines.Add(tmp);
            }
        }

这是在c#中读取文件的常用方法。 using 构造允许避免关闭 sr,因为在此之后指针立即被释放。

如果要使用列表的Sort 方法,现在必须实现 IComparable 接口

lass FoodData_SortByPriceByAscendingOrder : IComparer<FoodData>
{
    public int Compare(FoodData x, FoodData y)
    {
        if (x.Price > y.Price) return 1;
        else if (x.Price < y.Price) return -1;
        else return 0;
    }
}
class FoodData_SortByPriceByDescendingOrder : IComparer<FoodData>
{
    public int Compare(FoodData x, FoodData y)
    {
        if (x.Price < y.Price) return 1;
        else if (x.Price > y.Price) return -1;
        else return 0;
    }
}
class FoodData_SortByName : IComparer<FoodData>
{
    public int Compare(FoodData x, FoodData y)
    {
        return string.Compare(x.FoodName, y.FoodName);
    }
}

这 3 个类继承了 IComparer 接口(接收 FoodData 列表)。这并不难理解,但是here 你可以找到参考资料,here 是一个例子

完成课程后,您可以像这样从 main 调用这些:

FoodData_SortByPriceByAscendingOrder fAsc = new FoodData_SortByPriceByAscendingOrder();
        lines.Sort(fAsc);
        FoodData_SortByPriceByDescendingOrder fDesc = new FoodData_SortByPriceByDescendingOrder();
        lines.Sort(fDesc);
        FoodData_SortByName fByName = new FoodData_SortByName();
        lines.Sort(fByName);

【讨论】:

    【解决方案2】:

    yourChoicesPricesyourChoicesItems 未在给定代码中声明。这就是您收到此错误的原因。您需要声明它们。

    【讨论】:

      猜你喜欢
      • 2021-02-17
      • 1970-01-01
      • 2016-03-10
      • 1970-01-01
      • 2023-04-09
      • 2011-10-15
      • 1970-01-01
      • 2023-04-08
      相关资源
      最近更新 更多