输入字符串的不正确的格式 [英] Input string was not in a correct format

查看:142
本文介绍了输入字符串的不正确的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的C#,我在Java的一些基本知识,但我不能让这个code才能正常运行。

I'm new with C#, I have some basic knowledge in Java but I can't get this code to run properly.

这只是一个基本的计算器,但是当我运行程序VS2008给了我这个错误:

It's just a basic calculator, but when I run the program VS2008 gives me this error:

我几乎没有使用JSwing相同的程序,但在java中它完美地工作。

I did almost the same program but in java using JSwing and it worked perfectly.

下面是C#的形式:

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

namespace calculadorac
{
    public partial class Form1 : Form
    {

    int a, b, c;
    String resultado;

    public Form1()
    {
        InitializeComponent();
        a = Int32.Parse(textBox1.Text);
        b = Int32.Parse(textBox2.Text);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        add();
        result();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        substract();
        result();
    }

    private void button3_Click(object sender, EventArgs e)
    {
        clear();
    }

    private void add()
    {
        c = a + b;
        resultado = Convert.ToString(c);
    }

    private void substract()
    {
        c = a - b;
        resultado = Convert.ToString(c);
    }

    private void result()
    {
        label1.Text = resultado;
    }

    private void clear()
    {
        label1.Text = "";
        textBox1.Text = "";
        textBox2.Text = "";
    }
}

可以是什么问题?有没有办法解决这个问题的方法吗?

What can be the problem? Is there a way to solve it?

PS:我也试过

a = Convert.ToInt32(textBox1.text);
b = Convert.ToInt32(textBox2.text);

和它没有工作。

推荐答案

该错误是指字符串你试图解析一个整数实际上并不包含有效的整数。

The error means that the string you're trying to parse an integer from doesn't actually contain a valid integer.

这是非常不可能的文本框将包含时立即被创建的形式有效的整数 - 这就是你得到的整数值。它将使更多的意义更新 A B 在按钮的点击事件(在你以同样的方式在构造函数)。此外,检查出的 Int.TryParse 法 - 这是容易得多,如果该字符串可能不实际包含的整数使用 - 它不抛出一个异常,以便更容易恢复从

It's extremely unlikely that the text boxes will contain a valid integer immediately when the form is created - which is where you're getting the integer values. It would make much more sense to update a and b in the button click events (in the same way that you are in the constructor). Also, check out the Int.TryParse method - it's much easier to use if the string might not actually contain an integer - it doesn't throw an exception so it's easier to recover from.

这篇关于输入字符串的不正确的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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