提问人:fl1ckz 提问时间:1/11/2022 最后编辑:Chetanfl1ckz 更新时间:1/12/2022 访问量:236
尝试制作有异常的计算器
Trying to make calculator with exceptions
问:
所以我想在单击结果按钮后显示结果,但输入一个新数字会删除结果。就像计算器一样。
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void tlacitko0_Click(object sender, RoutedEventArgs e)
{
Button b = (Button)sender;
vys.Text += b.Content.ToString();
}
private void tlacitkovysledek_Click(object sender, RoutedEventArgs e)
{
try
{
vysledek();
}
catch (Exception)
{
vys.Text = "Chyba!";
}
}
private void vysledek()
{
string operace;
int nic = 0;
if (vys.Text.Contains("+"))
{
nic = vys.Text.IndexOf("+");
}
else if (vys.Text.Contains("-"))
{
nic = vys.Text.IndexOf("-");
}
else if (vys.Text.Contains("*"))
{
nic = vys.Text.IndexOf("*");
}
else if (vys.Text.Contains("/"))
{
nic = vys.Text.IndexOf("/");
}
else
{
}
operace = vys.Text.Substring(nic, 1);
double cislo1 = Convert.ToDouble(vys.Text.Substring(0, nic));
double cislo2 = Convert.ToDouble(vys.Text.Substring(nic + 1, vys.Text.Length - nic - 1));
if (operace == "+")
{
vys.Text += "=" + (cislo1 + cislo2);
}
else if (operace == "-")
{
vys.Text += "=" + (cislo1 - cislo2);
}
else if (operace == "*")
{
vys.Text += "=" + (cislo1 * cislo2);
}
else
{
vys.Text += "=" + (cislo1 / cislo2);
}
}
private void tlacitkoC_Click(object sender, RoutedEventArgs e)
{
vys.Text = "";
}
private void tlacitkozpet_Click(object sender, RoutedEventArgs e)
{
if (vys.Text.Length > 0)
{
vys.Text = vys.Text.Substring(0, vys.Text.Length - 1);
}
}
} `
我会尝试用英语将我的捷克语代码翻译给你
[
vys.Text = TextBox.Text ;
tlacitko(x) = button(x) ;
vysledek = result ;
nic = nothing ;
operace = operation ;
cislo(x) = number(x) ;
chyba = error ;
]
希望它能有所帮助..
另外,想在除以零时例外,我对 c# 和 wpf 很陌生,尽管我在学校用它编码了大约半年,所以如果你能对我放轻松,请。
我很迷茫,不知道该在哪里破例除法。.但我认为在结果后单击新数字时,我可以尝试使 vys.text = “”;也不知道放在哪里。.
非常感谢您抽出时间接受采访。
谢谢!
答:
0赞
valentin
1/11/2022
#1
您可以使用文本框更改事件并删除文本框中的文本。 代码如下所示:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e) {
var box = (TextBox)sender;
if (box.Text.StartsWith(result) && textBox.Text != result) {
textBox.Text = textBox.Text.Remove(0, result.Length);
textBox.SelectionStart = 1;
}
}
编辑:
该函数用于您的 xaml-File,有人认为是这样的:TextBox_TextChanged
<TextBox x:Name="vys" TextChanged="TextBox_TextChanged"/>
检查 textBox 中的值是否为计算结果。以便在用户键入新号码时删除旧结果。
该值是计算的结果字符串,应为包含计算结果的全局变量。result
对于除以 0,您可以更改 else 语句
else
{
vys.Text += "=" + (cislo1 / cislo2);
}
像这样:
else
{
if(cislo2 != 0){
vys.Text += "=" + (cislo1 / cislo2);
} else {
//Print an error or thow an exception
}
}
评论
0赞
fl1ckz
1/11/2022
private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { var box = (TextBox)sender; if (box.Text.StartsWith(result) && textBox.Text != result) { textBox.Text = textBox.Text.Remove(0, result.长度);textBox.SelectionStart = 1;} } 不知道该怎么办?
评论