c# - TryParse 不工作,如果其他条件不工作
问题描述
我正在尝试制作一个可以将摄氏温度转换为华氏温度或反之亦然的正常形式。
private void button1_Click(object sender, EventArgs e)
{
double celsius;
double fahrenheit;
string value;
double finalValue;
bool successCelsius = double.TryParse(textBox1.Text, out celsius);
bool successFahrenheit = double.TryParse(textBox2.Text, out fahrenheit);
if (successCelsius == false)
{
label6.Text = ("ERROR: Please enter a numeric temperature to convert.");
return;
}
else
{
celsius = Convert.ToDouble(textBox1.Text);
finalValue = (celsius * 9) / 5 + 32;
label6.Text = finalValue.ToString();
label6.Text = celsius + " " + "degrees Celsius converts to" + " " + finalValue + " " + "degrees Fahrenheit";
}
if (successFahrenheit == false)
{
label6.Text = ("ERROR: Please enter a numeric temperature to convert.");
return;
}
else
{
fahrenheit = Convert.ToDouble(textBox2.Text);
finalValue = (fahrenheit - 32) * 5 / 9;
value = finalValue.ToString();
label6.Text = fahrenheit + " " + "degrees Fahrenheit converts to" + " " + finalValue + " " + "degrees Celsius";
}
}
文本框接受这些值并显示到 label6。它检查输入的值是否为双精度值,然后它可以工作。idk 为什么 tryParse 不起作用。
你能帮我吗?:)
解决方案
这段代码不能“工作”的原因是你的代码流。
现在代码的结构方式,您必须同时输入摄氏和华氏值,否则您的代码将显示“错误”。如果 textbox1 或 textbox2 为空,您的代码将从 TryParse 返回 false。如果您遵循该逻辑,则将执行此代码(如果您只输入摄氏度):
if (successFahrenheit == false)
{
label6.Text = ("ERROR: Please enter a numeric temperature to convert.");
return;
}
更新:您需要分别处理这两种情况......这是一种简单的方法......检查一个并执行......否则,检查另一个。有很多方法可以“解决”这个问题,但这将是最简单的方法之一。
private void button1_Click(object sender, EventArgs e)
{
double celsius;
double fahrenheit;
string value;
double finalValue;
if (textBox1.Text.Length > 0)
{
bool successCelsius = double.TryParse(textBox1.Text, out celsius);
if (successCelsius == false)
{
label6.Text = ("ERROR: Please enter a numeric temperature to convert.");
return;
}
else
{
celsius = Convert.ToDouble(textBox1.Text);
finalValue = (celsius * 9) / 5 + 32;
label6.Text = finalValue.ToString();
label6.Text = celsius + " " + "degrees Celsius converts to" + " " + finalValue + " " + "degrees Fahrenheit";
}
}
else
{
bool successFahrenheit = double.TryParse(textBox2.Text, out fahrenheit);
if (successFahrenheit == false)
{
label6.Text = ("ERROR: Please enter a numeric temperature to convert.");
return;
}
else
{
fahrenheit = Convert.ToDouble(textBox2.Text);
finalValue = (fahrenheit - 32) * 5 / 9;
value = finalValue.ToString();
label6.Text = fahrenheit + " " + "degrees Fahrenheit converts to" + " " + finalValue + " " + "degrees Celsius";
}
}
}
推荐阅读
- javascript - 将 javascript 代码添加到 Wordpress 中的侧边栏小部件区域
- python - 使用 for 循环创建字典,而不是将其转换为带有索引的数据框
- css - 带有无效边框颜色的边框如何工作?
- arduino - BLE CSC 服务并不总是被检测到 - 正确设置?
- reactjs - 修复 React JS 上的编辑功能很热门?
- c# - C# 中的隐式类型转换
- android - java.lang.RuntimeException:从@HiltAndroidTest 生成的 Hilt 类丢失
- android - 我已经从平台工具中删除了 adb 文件
- javascript - 如何为特定国家/地区运行 JavaScript 文件?
- python - 如何安排 python 电报机器人在特定时间/之后发送消息?