我一直在做codeeval練習: https://www.codeeval.com/open_challenges/30/submit/?lid=1335504長度不能爲負(例外)
這裏是我的代碼
using System;
using System.Text;
using System.IO;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
using (StreamReader reader = File.OpenText(args[0]))
while (!reader.EndOfStream)
{
StringBuilder result = new StringBuilder();
string b = "";
string c = "";
string[] b2;
string[] c2;
int x = 0;
string line = reader.ReadLine();
if (null == line)
continue;
// do something with line
else{
x = line.IndexOf(";");
b = line.Substring(x +1);
b2 = b.Split(',');
c = line.Substring(0, (line.Length - ((b.Length) + 1)));
c2 = c.Split(',');
foreach (string u in b2) {
foreach (string i in c2)
{
if (int.Parse(u) == int.Parse(i))
{
result.Append(u + ",");
}
}
}
Console.WriteLine(result.ToString().Substring(0, result.Length - 1));
result.Clear();
Array.Clear(b2, 0 , b2.Length);
Array.Clear(c2, 0 , c2.Length);
}
}
}
}
,當我在我的VS運行,它可以在1串。然而,它運行一兩行,然後當我在codeeval上運行它時,會給我一個懷疑。我不知道爲什麼長度可以是負的...?
未處理的異常:System.ArgumentOutOfRangeException:不能爲 否定。參數名稱:System.String.Substring的長度(Int32 startIndex,Int32長度)[0x00000] in:0 at Program.Main(System.String [] args)[0x00000] in:0 [ERROR] FATAL UNHANDLED EXCEPTION :System.ArgumentOutOfRangeException: 不能爲負數。參數名稱:長度在 System.String.Substring(的Int32的startIndex,的Int32長度)[0x00000]在 :0在Program.Main(System.String []參數) [0x00000]在:0
輸入是
68,69,70,71,72,73,74,75,76,77,78,79,80,81,82;78,79,80,81,82,83,84
87,88,89,90,91,92,93;64,65,66,67,68
87,88,89,90,91,92;81,82,83,84,85,86,87
82,83,84,85,86;68,69,70,71,72,73,74,75,76,77,78,79,80
78,79,80,81,82,83,84,85,86,87,88,89,90,91;67,68,69,70,71,72
編輯鏈接:https://www.codeeval.com/open_challenges/30/ –
'(line.Length - ((b.Length)+ 1))'返回一個負數。你需要弄清楚爲什麼'b'比'line'或者result.Length - 1'返回一個負數(也就是'result'是一個空字符串)。 – ChrisF
使用調試並查看發生了什麼。 – mybirthname