【发布时间】:2019-03-26 22:25:25
【问题描述】:
我试图弄清楚为什么当我运行我的程序并按下提交按钮时,我收到一条错误消息,指出我的列表格式错误。该程序的一些背景知识:这是针对我的可视化编程课程的。该程序适用于银行帐户。我试图评论每个部分的内容以使其更易于阅读
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//Tab 1 Create and close account
private void Submitbtn_Click(object sender, EventArgs e)
{
double x;
if (OpenRdo.Checked == true && Nametxtbx.TextLength > 0)
{
double.TryParse(Nametxtbx.Text, out x);
// after clicking the button there is
// no number; it says system.random
Random acct = new Random();
int AccountNumber = acct.Next(5, 1000);
outputlbl.Text = acct.ToString();
}
// list for accounts
// This is where it says I have the error
// that my list is in the wrong format
var accounts = new List<Account>
{
new Account(Nametxtbx.Text, double.Parse(outputlbl.Text), 0)
};
// Write these records to a file
WriteFile(accounts);
// message box when you create account
if (ValidateChildren(ValidationConstraints.Enabled))
{
MessageBox.Show("Account Created", "Message",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
//writing to the file
static void WriteFile(List<Account> accts)
{
StreamWriter outputFile = File.CreateText("accounts.txt");
string record;
foreach (var acct in accts)
{
record = $"{acct.Name},{acct.Balance}";
Console.WriteLine($"Writing record: {record}");
outputFile.WriteLine(record);
}
outputFile.Close();
}
}
【问题讨论】:
-
通常,该异常的含义正是它所说的:根据使用的文化(默认情况下从 Windows 检索),这不是有效的双精度。
-
(A) 注意错误信息的内容(是英文的,应该能看懂)。 (B) 注意哪个代码行的哪个方法调用产生了错误。 (C) 你现在有了解决问题的知识。 (D) 利润! ;)
-
看看您现在是否可以将大型复制器缩减为一到三行的程序。这将比您发布的代码更容易理解和诊断,其中 95% 与您的问题完全无关。
-
@elgonzo:嗯,这还需要知道您的文化书写数字的方式并不是书写数字的唯一方式。奇怪的是,很多说英语的人在遇到这个例外之前都没有明白这一点。
-
这一行是否正确(
Nametxtbx是否应该包含双精度?):double.TryParse(Nametxtbx.Text, out x);此外,TryParse调用通常是if条件的一部分(其中else将是向用户显示他们需要输入有效数字的消息)。另外,你在这个方法之后从不使用变量x,那么它的目的是什么?
标签: c#