出于某些原因,无法解析为Int. [英] Parsing to Int doesn't work for some reason.

查看:78
本文介绍了出于某些原因,无法解析为Int.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此方面浪费了大量时间.我认为它应该"起作用,但是我找不到它出了什么问题.

Been wasting a lot of time on this. I think it ''should'' work, but I can''t find what''s wrong with it.

protected int Checkscore(Node x)
    {
            string[] numbers = x.GetProperty("answers").Value.Split(';');
            int score = 0;
            foreach (string n in numbers)
            {
          //      score += int.Parse(n);
                LabelMonitor.Text += n + " ";
            }
            
            return score;
    }



属性答案"如下所示:"1; 100; 1; 50;"
"LabelMonitor"显示如下:"1100 1 50"

因此,解析并正确计算它们应该没问题吗?
但是,如果我取消注释另一行,则会引发异常:

输入字符串的格式不正确."

有人知道我做错了吗?我要疯了. :-s



The property "answers" looks like this: "1;100;1;50;"
And "LabelMonitor" shows this: "1 100 1 50"

So, it should be okay to parse and count them all up right?
Yet, if I uncomment the other line, it throws an exception:

"Input string was not in a correct format."

Does anyone know what I did wrong? I''m going crazy. :-s

推荐答案

尝试以下方法:
Try this :
if(n!="") score += int.Parse(n);


您是否尝试过Convert.ToInt32(n).与int.Parse相比,我似乎更幸运,尤其是从数据库转换结果时.
Have you tried Convert.ToInt32(n). I seem to have more luck with that than with int.Parse, especially when converting results from a database.


Mehdi Gholam给出的解决方案有效,但是这种替代方案也解决了您的问题. br/>
The solution given by Mehdi Gholam works, but this alternative also solves your problem.

protected int Checkscore(Node x)
    {
            char[] delimiter = {';'};
            string[] numbers = x.GetProperty("answers").Value.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
            int score = 0;
            foreach (string n in numbers)
            {
                score += int.Parse(n);
                LabelMonitor.Text += n + " ";
            }
            
            return score;
    }



StringSplitOptions.RemoveEmptyEntries [ Split [ ^ ]函数删除所有空结果.



为了确保当字符串包含非数字字符时代码也能正常工作,您应该使用 Int32.TryParse [ ^ ].
使用TryParse时,您还会处理Split函数的空结果,因此可以再次使用对Split函数的原始调用.



The StringSplitOptions.RemoveEmptyEntries[^] option tells the Split[^] function to remove all empty results.



To make sure the code also works when the string contains non digit characters you should use Int32.TryParse[^].
When using TryParse you also deal with the empty result from the Split function, so you can use your original call to the Split function again.

protected int Checkscore(Node x)
    {
            string[] numbers = x.GetProperty("answers").Value.Split(';');
            int score = 0;
            int parseResult = 0;

            foreach (string n in numbers)
            {
		if (Int32.TryParse(n, out parseResult))
                	score += parseResult;
                LabelMonitor.Text += n + " ";
            }
            
            return score;
    }


这篇关于出于某些原因,无法解析为Int.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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