如何将字符串转换为Int [英] How Do I Convert Strings To Int

查看:70
本文介绍了如何将字符串转换为Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个文本框,一个输入小时,一个数字和一个电价和一个按钮

但是每当我尝试在文本框中输入值时都会有一个formatException。

我怎么能这样做呢?

每当我编译它运行良好但我无法输入值

帮助请

谢谢!

i am having three textboxes one inputting hours ,one numbers and one power rate and a button
but am having a formatException whenever i try to input values in the textboxes.
How can i fore go this please?
whenever i compile it runs well but i am unable to input the values
help please
Thanks!

int num1 = int.Parse(TextBox1.Text);
             
             double num2 = double.Parse(TextBox2.Text;);
            
             int num3 = int.Parse(TextBox3.Text;);
             soln1 = num1 * num2 * num3;
             MessageBox.Show(soln1.ToString());

推荐答案

而不仅仅是转换值,最好是使用TryParse来测试是否可以转换值,如果可以,它将被转换。看一下 Int.TryParse [< a href =https://msdn.microsoft.com/en-us/library/system.int32.tryparse(v=vs.110).aspx\"target =_ blanktitle =New Window> ^ ]和 double.TryParse [< a href =https://msdn.microsoft.com/en-us/library/system.double.tryparse(v=vs.110).aspx\"target =_ blanktitle =New Window> ^ ]



类似

Instead of just converting the values it would be better to use TryParse to test if the value can be converted and if it can, it'll be converted. Have a look at Int.TryParse[^] and double.TryParse[^]

Something like
double num2;
if (!double.Parse(TextBox2.Text, out num2)) {
   System.Diagnostics.Debug.WriteLine(string.Format("{0} is not a double.", TextBox2.Text));
   return;
}





请注意,您最初有一个额外的分号



Note that you originally had an extra semicolon in

double num2 = double.TryParse(TextBox2.Text;);


您有两个选择:按照建议使用 TryParse 方法,或处理抛出的异常。无论哪种方式,您都应明确处理可能的无效用户输入。例如,您可以显示一个消息框,说明给定字段的格式要求是什么。
You have two options: use, as suggested, the TryParse methods, or handle the thrown exceptions. In either ways you should explicitely deal with possible invalid user inputs. For instance, you may show a message box explaining what are the format requirements for the given field.


int value;
if (Int32.TryParse("50", out value))
    Console.WriteLine(value);
else
    Console.WriteLine("Failed to parse the string value to integer.");


这篇关于如何将字符串转换为Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆