C#程序Write2函数出现数组越界错误,寻求调试帮助
数组越界问题排查:寻找最长非数字序列的C#代码错误
我正在完成一项编程练习,需求是输入一段文本后,找出其中最长的非数字序列(规则:遇到数字即分割序列,仅需统计序列长度)。我的C#程序中,Write2函数负责实现该功能,但第43行出现了**数组越界(Out of bounds of Array)**错误。尝试多种方法仍未解决,恳请帮助!
测试输入:Xyz7jkl9ylk2XZjwasd
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VeryHigh2 { //Xyz7jkl9ylk2XZjwasd internal class Program { static void Main(string[] args) { string word = Console.ReadLine(); int n = word.Length / 4; Console.WriteLine(" IZLAZI \n-------------ODGOVOR 1-------------\n"); Write1(word); Console.WriteLine("\n-------------ODGOVOR 1-------------\n"); Write2(word,n); } static void Write2(string word,int n) { int[] Sequence = new int[n]; string s = ""; int i = 0; int counter = 1; while(i < Sequence.Length) { for (int t = 0; t < word.Length; t++) { char c = word[t]; if (c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9') { counter++; if (s == "") { continue; } else { int a = s.Length; Sequence[i] = a; s = ""; i++; } continue; } else { s = s + Convert.ToString(c); counter++; } } if (counter == word.Length) { Sequence[i] = s.Length; int b = Sequence.Length; i = b; } } int max = Sequence[0]; for(int j = 1; j < Sequence.Length; j++) { if(max < Sequence[j]) { max = Sequence[j]; } } Console.WriteLine(max); } static void Write1(string word) { int counter1 = 0; int counter2 = 0; string lower = word.ToLower(); string upper = word.ToUpper(); char l = lower[0]; char u = upper[0]; for(int i = 0; i < word.Length; i++) { if(l == word[i] || u == word[i]) { counter1++; } } for(int i = 1; i < word.Length; i++) { l = lower[i]; u = upper[i]; for(int a = 0; a < word.Length; a++) { if (word[a] == l || word[a] == u) { counter2++; } } if(counter2 == counter1) { goto counter; } else { Console.WriteLine("Tekst nije uravnotezen!"); break; } counter: counter2 = 0; if(i == word.Length - 1) { Console.WriteLine("Tekst je uravnotezen!"); } } } } }
已尝试的解决方法:
- 调整while循环的逻辑
- 直接赋值要插入数组的变量
内容的提问来源于stack exchange,提问作者Nikola Ivaniš
相关产品推荐
相关产品推荐

