c# - CultureInfo.GetCultureInfo 导致不正确的格式错误
问题描述
每次当我输入 z 作为输入时,它都会失败。我不明白问题是什么。它收到错误“System.FormatException:输入字符串的格式不正确” Dsales 是一个进入转换器以转换为美元和美分的整数。这有什么不正确的?
using System;
using static System.Console;
using System.Globalization;
class HomeSales
{
static void Main()
{
string response;
int dsales = 0;
int esales = 0;
int fsales = 0;
int initial;
string damount;
string eamount;
string famount;
int damounti;
int eamounti;
int famounti;
WriteLine ("Enter a salesperson initial");
response = ReadLine();
//initial = Convert.ToInt32(response);
while (response == "d" || response == "D")
{
WriteLine ("Enter Line of sale");
damount = ReadLine();
damounti = Convert.ToInt32(damount);
dsales = dsales + damounti;
}
while (response == "z" || response == "Z")
{
WriteLine("Danielle sold {0}", dsales.ToString("C", CultureInfo.GetCultureInfo("en-US")));
}
}
}
解决方案
您错误地编写了控制台循环。
从您的变量声明和字符串来看,您的代码打算记录不同销售人员的销售额,并在完成销售条目时报告总销售额。
当FormatException
您在“输入销售行”提示后键入“z”时出现。
不要假设用户总是会输入一个有效的数字,而是在尝试解析一个数字之前添加一个条件来检查有效的输入。条件检查还应该包括提前退出循环的方法,或者至少避免解析数值的代码。
此外,当您处理解释为货币的值时,请考虑使用 System.Decimal ( decimal
) 结构来存储值,因为计算会更准确。
推荐阅读
- coldfusion - 将 Microsoft DPAPI 与 Coldfusion 一起使用
- c# - 使用 (XALM) 构建过程模板在 TFS 2013 中将工具路径设置为 MSBuild 2019
- python - 缩进 beetwen 键和值
- docker - 容器构建错误 - 无法关闭容器 - 容器在关闭期间遇到错误
- python - Python:从 argmin 在 3D 数组中广播 2D 索引数组
- android - 如何删除 RecycleView 项目之间的空格?
- ajax - Yii2 Pjax 更新 div 与 flash 消息问题
- forum - 如何将文件附加到此论坛中的答案?
- bash - 如何在单个 awk 命令中组合多个正则表达式条件?
- javascript - 添加 javascript 导致 div 不显示在网站上