【问题标题】:Input string was not in a correct format输入字符串的格式不正确
【发布时间】:2022-01-23 23:11:21
【问题描述】:

我是 C# 新手,我有一些 Java 基础知识,但我无法让这段代码正常运行。

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

我做了几乎相同的程序,但在 java 中使用 JSwing 并且运行良好。

这是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 = "";
    }
}

可能是什么问题?有办法解决吗?

PS:我也试过

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

它没有用。

【问题讨论】:

    标签: c# exception formatexception


    【解决方案1】:

    该错误意味着您尝试从中解析整数的字符串实际上并不包含有效整数。

    创建表单时文本框极不可能立即包含有效整数 - 这是您获取整数值的地方。在按钮单击事件中更新ab 会更有意义(与在构造函数中的方式相同)。另外,请查看Int.TryParse 方法 - 如果字符串实际上可能不包含整数,它会更容易使用 - 它不会引发异常,因此更容易从中恢复。

    【讨论】:

    • 当尝试从具有不同文化信息的用户输入 Convert.ToDouble 时,也可能会抛出此错误消息,因此您可以使用 Convert.ToDouble (String, IFormatProvider) 而不仅仅是 Convert.ToDouble (String) .很难调试,因为程序可以在你的系统上运行,但会在它的一些用户上抛出错误,这就是为什么我有一种方法可以在我的服务器上记录错误并且我很快就发现了问题。
    【解决方案2】:

    我遇到了这个确切的异常,除了它与解析数字输入无关。所以这不是对 OP 问题的回答,但我认为分享知识是可以接受的。

    我声明了一个字符串,并将其格式化为与需要大括号 ({}) 的 JQTree 一起使用。您必须使用双花括号才能将其作为格式正确的字符串接受:

    string measurements = string.empty;
    measurements += string.Format(@"
        {{label: 'Measurement Name: {0}',
            children: [
                {{label: 'Measured Value: {1}'}},
                {{label: 'Min: {2}'}},
                {{label: 'Max: {3}'}},
                {{label: 'Measured String: {4}'}},
                {{label: 'Expected String: {5}'}},
            ]
        }},",
        drv["MeasurementName"] == null ? "NULL" : drv["MeasurementName"],
        drv["MeasuredValue"] == null ? "NULL" : drv["MeasuredValue"],
        drv["Min"] == null ? "NULL" : drv["Min"],
        drv["Max"] == null ? "NULL" : drv["Max"],
        drv["MeasuredString"] == null ? "NULL" : drv["MeasuredString"],
        drv["ExpectedString"] == null ? "NULL" : drv["ExpectedString"]);
    

    希望这将帮助其他发现此问题但未解析数字数据的人。

    【讨论】:

    • 对于如何在 C# 中解析整数的问题,这是如何获得 66 次赞成的答案?
    【解决方案3】:

    如果您没有明确验证文本字段中的数字,无论如何最好使用

    int result=0;
    if(int.TryParse(textBox1.Text,out result))
    

    现在如果结果成功,那么您可以继续计算。

    【讨论】:

    • 通常result 不需要初始化。
    【解决方案4】:

    问题

    出现错误的可能情况有:

    1. 因为textBox1.Text只包含数字,但数字是too big/too small

    2. 因为textBox1.Text 包含:

      • a) 非数字(开头/结尾的space 和开头的- 除外)和/或
      • b) 代码的应用区域性中的千位分隔符未指定 NumberStyles.AllowThousands 或您指定 NumberStyles.AllowThousands 但在区域性中输入错误的 thousand separator 和/或
      • c) 小数点分隔符(int 解析中不应存在)

    不好的例子:

    案例一

    a = Int32.Parse("5000000000"); //5 billions, too large
    b = Int32.Parse("-5000000000"); //-5 billions, too small
    //The limit for int (32-bit integer) is only from -2,147,483,648 to 2,147,483,647
    

    案例 2 a)

    a = Int32.Parse("a189"); //having a 
    a = Int32.Parse("1-89"); //having - but not in the beginning
    a = Int32.Parse("18 9"); //having space, but not in the beginning or end
    

    案例 2 b)

    NumberStyles styles = NumberStyles.AllowThousands;
    a = Int32.Parse("1,189"); //not OK, no NumberStyles.AllowThousands
    b = Int32.Parse("1,189", styles, new CultureInfo("fr-FR")); //not OK, having NumberStyles.AllowThousands but the culture specified use different thousand separator
    

    案例 2 c)

    NumberStyles styles = NumberStyles.AllowDecimalPoint;
    a = Int32.Parse("1.189", styles); //wrong, int parse cannot parse decimal point at all!
    

    看似不行,但实际上可以示例:

    情况 2 a) 正常

    a = Int32.Parse("-189"); //having - but in the beginning
    b = Int32.Parse(" 189 "); //having space, but in the beginning or end
    

    情况 2 b) 正常

    NumberStyles styles = NumberStyles.AllowThousands;
    a = Int32.Parse("1,189", styles); //ok, having NumberStyles.AllowThousands in the correct culture
    b = Int32.Parse("1 189", styles, new CultureInfo("fr-FR")); //ok, having NumberStyles.AllowThousands and correct thousand separator is used for "fr-FR" culture
    

    解决方案

    在所有情况下,请使用您的 Visual Studio 调试器检查textBox1.Text 的值,并确保它在int 范围内具有完全可接受的数字格式。像这样的:

    1234
    

    另外,你可以考虑

    1. 使用TryParse而不是Parse来确保未解析的数字不会导致您出现异常问题。
    2. 检查TryParse的结果,如果不是true则处理

      int val;
      bool result = int.TryParse(textbox1.Text, out val);
      if (!result)
          return; //something has gone wrong
      //OK, continue using val
      

    【讨论】:

      【解决方案5】:

      您没有提到您的文本框是否在设计时或现在具有值。表单初始化时,如果在表单设计时没有将文本框放入文本框,则文本框可能没有值。您可以通过在 desgin 中设置 text 属性将 int 值放入表单设计中,这应该可以工作。

      【讨论】:

        【解决方案6】:

        在我的情况下,我忘了放双花括号来逃避。 {{myobject}}

        【讨论】:

        • 什么?怎么回答这个问题?我们甚至不知道“你的情况”是什么......
        • @zawhtut 在您回答 OP 的问题时大约 7 岁。您需要澄清您的情况到底是什么,以及如何放置双花括号来解决您遇到的问题。您还应该包括有关正在使用的语言的详细信息。 OP的问题涉及c#。您对双花括号“{{}}”的提及与上下文无关,但强烈建议您使用不同的语言或模板库,这对 OP 的场景没有影响或好处。
        【解决方案7】:

        当您使用带有无效括号语法的字符串格式化程序时,您可能会遇到此异常。

        // incorrect
        string.Format("str {incorrect}", "replacement")
        
        // correct
        string.Format("str {1}", "replacement")
        

        【讨论】:

        • 我的第一个参数“{ 0:c2}”前面有一个空格,导致了它。
        【解决方案8】:

        这也是我的问题.. 在我的情况下,我将波斯号码更改为拉丁号码并且它有效。 并在转换之前修剪你的字符串。

        PersianCalendar pc = new PersianCalendar();
        char[] seperator ={'/'};
        string[] date = txtSaleDate.Text.Split(seperator);
        int a = Convert.ToInt32(Persia.Number.ConvertToLatin(date[0]).Trim());
        

        【讨论】:

          【解决方案9】:

          我有一个类似的问题,我用以下技术解决了:

          以下代码行引发了异常(见下面用**修饰的文字):

          static void Main(string[] args)
              {
          
                  double number = 0;
                  string numberStr = string.Format("{0:C2}", 100);
          
                  **number = Double.Parse(numberStr);**
          
                  Console.WriteLine("The number is {0}", number);
              }
          

          经过一番调查,我意识到问题在于格式化字符串包含 Parse/TryParse 方法无法解析的美元符号 ($)(即剥离)。因此,使用字符串对象的 Remove(...) 方法,我将行更改为:

          number = Double.Parse(numberStr.Remove(0, 1)); // Remove the "$" from the number
          

          此时 Parse(...) 方法按预期工作。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-08-22
            相关资源
            最近更新 更多