gpt4 book ai didi

c# - Try and catch,总是捕获异常

转载 作者:行者123 更新时间:2023-12-02 21:45:29 25 4
gpt4 key购买 nike

我想做的是,从文本框中获取用户输入,将其转换为 int,然后使用它。除了 try and catch 之外,我一切都正常工作。如果这个人输入的是字母而不是数字。使用下面的代码它总是捕获一些东西。我不知道是什么捕获了一些东西。我已经取出了 bool 测试,如果我输入一封信,它只会抛出异常,然后发出蜂鸣声。其他则等待有效输入。请原谅我乱七八糟的代码,我仍然是一个初学者 C# 程序员:D 提前感谢!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
bool tone = false;
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
bool test = true;
speedInput.Clear();
beep.Clear();
int beepspeed = 90;
int speed = 100;
string speedtext = this.speedInput.Text;
string beeptext = this.beep.Text;
try
{
test = true;
beepspeed = Convert.ToInt32(beeptext);
speed = Convert.ToInt32(speedtext);
}
catch (Exception)
{
MessageBox.Show("numbers above 37 only!!");
test = false;
}

if (test)
{
for (int i = 0; i < beepspeed; i++)
{
if (this.tone)
{
Random ran = new Random();
int rand = ran.Next(400, 3000);
Console.Beep(rand, speed);
}
else
{
Console.Beep(1000, speed);
}
}
}
}

private void radioButtonYes_CheckedChanged(object sender, EventArgs e)
{
this.tone = true;
}

private void radioButtonNo_CheckedChanged(object sender, EventArgs e)
{
this.tone = false;
}
}
}

最佳答案

您正在清理button1_click开头的输入内容

speedInput.Clear();
beep.Clear();

然后,当您尝试将空字符串转换为 int32 时,它会失败

beepspeed = Convert.ToInt32(beeptext);
speed = Convert.ToInt32(speedtext);

关于c# - Try and catch,总是捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19601121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com