我的文本文件将不会读取到数组中
本文关键字:读取 数组 文本 文件 我的 | 更新日期: 2023-09-27 17:57:12
此问题已得到回答。我对C#还比较陌生,遇到了一个问题。我的程序每次尝试捕获都会抛出一个错误。我检查了所有的东西,改变了一些东西,但似乎什么都不起作用。错误发生在第49行(读取文本文件的while循环发生在该行(。有人知道可能是什么问题吗??我知道最小值/最大值/平均值可能还有其他问题,但我能解决。我只是真的需要有人帮我修复将文件读取到数组中的问题。
错误代码为:输入字符串的格式不正确。位于System.Number.StringToNumber使用System.Collections.Generic;使用System.ComponentModel;使用System.Data;使用System.Drawing;使用System.Linq;使用System.Text;使用System.Windows.Forms;使用System.IO;
namespace Total_Sales_BBrantley
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalc_Click(object sender, EventArgs e)
{
try
{
// Declare variable to hold the amount of sales
// Declare a constant for the array size
const int SIZE = 100;
// Create an array for the sales
double[] allSales = new double[SIZE];
// Declare a variable for holding the total value of sales
double total = 0.0;
// Declare a variable to hold the average
double average;
// Declare a variable to hold the highest value
double highest = double.MinValue;
// Declare a variable to hold the lowest value
double lowest = double.MaxValue;
int count = 0;
// Declare a StreamReader variable.
StreamReader readFile;
// Open the file and get a StreamReader object using a relative path
readFile = File.OpenText("Sales.txt");
while (!readFile.EndOfStream && count < allSales.Length)
{
ERROR ERROR ERROR: [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ allSales[count] = int.Parse(readFile.ReadLine()); ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
// Increment count
count++;
}
// Close the file
readFile.Close();
lstSales.Items.Add("The file contains " + count + " items:");
for (int index = 0; index < count; index++)
{
lstSales.Items.Add(allSales[index]);
}
// Display the total
double sum = allSales.Sum();
lblTotal.Text = sum.ToString();
total += sum;
average = total / allSales.Length;
lblAverage.Text = average.ToString();
for (int index = 1; index < allSales.Length; index++)
{
if (allSales[index] > highest)
{
highest = allSales[index];
}
lblHighest.Text = highest.ToString();
}
for (int index = 1; index < allSales.Length; index++)
{
if (allSales[index] < lowest)
{
lowest = allSales[index];
}
lblLowest.Text = lowest.ToString();
}
}
catch (Exception ex)
{
// Display an error message on bad input from file
MessageBox.Show(string.Concat("Error calculating the sales. ", ex.Message, "'r'n", ex.StackTrace));
}
}
private void btnExit_Click(object sender, EventArgs e)
{
//Closes the application
this.Close();
}
}
}
我认为问题在于您使用的是int.Parse而不是double。作语法分析
这就是你的问题:
allSales[count] = int.Parse(readFile.ReadLine());
您的数组是一个Double数组,并且您正在将字段分配给一个整数值。将该行解析为Double,而不是int.
allSales[count] = Double.Parse(readFile.ReadLine());