[英]Calculator App Crash when using “Enter” Key
I am trying to write a graphical calculator, So far the calculator works, but I want to use the Key "Enter" for it to perform the operation and give the answer. 我正在尝试编写图形计算器,到目前为止该计算器可以运行,但是我想使用“ Enter”键来执行该操作并给出答案。 For now it just crashes whenever I press Enter
. 现在,只要按Enter
它就会崩溃。 This is the XAML code: 这是XAML代码:
<TextBox Height="38" TextWrapping="Wrap" VerticalAlignment="Top"
Margin="16,23,0,0" HorizontalAlignment="Left" Width="226"
FontSize="20" Background="Black" BorderThickness="2" Name="tb"
Text="" KeyUp="KeyDownHandler">
Here is the code that handles the Enter
key event. 这是处理Enter
键事件的代码。
private void KeyDownHandler(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Enter)
{
result();
}
}
private void result()
{
String op;
int iOp = 0;
if (tb.Text.Contains("+"))
{
iOp = tb.Text.IndexOf("+");
}
else if (tb.Text.Contains("-"))
{
iOp = tb.Text.IndexOf("-");
}
else if (tb.Text.Contains("*"))
{
iOp = tb.Text.IndexOf("*");
}
else if (tb.Text.Contains("/"))
{
iOp = tb.Text.IndexOf("/");
}
else
{
//error
}
op = tb.Text.Substring(iOp, 1);
double num1 = Convert.ToDouble(tb.Text.Substring(0, iOp));
double num2 = Convert.ToDouble(tb.Text.Substring(iOp + 1, tb.Text.Length - iOp - 2));
if (op == "+")
{
tb.Text = Convert.ToString(num1 + num2);
}
else if (op == "-")
{
tb.Text = Convert.ToString(num1 - num2);
}
else if (op == "*")
{
tb.Text = Convert.ToString(num1 * num2);
}
else if (op == "/")
{
tb.Text = Convert.ToString(num1 / num2);
}
}
I am beginner in C#, XAML and Visual Studio. 我是C#,XAML和Visual Studio的初学者。 Is this the right way of handling the Enter.key event? 这是处理Enter.key事件的正确方法吗?
This is the exception thrown: 这是引发的异常:
Exception thrown: 'System.FormatException' in mscorlib.ni.dll 引发异常:mscorlib.ni.dll中的“ System.FormatException”
Change this: 更改此:
double num2 = Convert.ToDouble(tb.Text.Substring(iOp + 1, tb.Text.Length - iOp - 2));
To this: 对此:
double num2 = Convert.ToDouble(tb.Text.Substring(iOp + 1, tb.Text.Length - iOp - 1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.