【问题标题】:How to avoid System.ArgumentOutOfRangeException in using Substring and length method如何在使用 Substring 和 length 方法时避免 System.ArgumentOutOfRangeException
【发布时间】:2021-11-26 13:44:10
【问题描述】:

我正在创建一个猜谜游戏,但每次我第二次输入正确的字符时它都会抛出异常,但起初看起来很好,但当我再次猜到正确的字母时,我得到异常,异常是 System.ArgumentOutOfRangeException : 'startIndex 不能大于字符串的长度。 (参数'startIndex')我尝试了所有可能的方法来解决这个问题,但我仍然找不到正确的解决方案希望你能帮助我。

using System;
using System.Collections;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            String secret = " ", temp = " ", lalagyan = " ", answer="";
            int count = 0, num = 5;
            bool bol = false;
            var random = new Random();
            ArrayList list = new ArrayList { "one", "two", "three", "four" };
            int index = random.Next(list.Count);
            String word = list[index].ToString();

            for (int i = 0; i < word.Length; i++)
            {
                secret = word.Replace(word, "-");
                Console.Write(secret);
            }
            do
            {
                count++;
                Console.WriteLine("\nEnter a letter ");
                Console.WriteLine("Remaining Chances: " + num);
                Console.WriteLine("Clue: the word is " + word.Length + " letters");
                Console.Write("Answer: ");
                answer = Console.ReadLine();
                num--;
                Console.WriteLine("");
                for (int i = 0; i < word.Length; i++)
                {
                    //dito
                    if (answer.Equals(Convert.ToString(word[i])))
                    {
                        if (!bol)
                        {
                            temp += Convert.ToString(word[i]);
                        }
                        else
                        {
                            //error around here
                            Console.Write("Correct Letter\n");
                            lalagyan = Convert.ToString(word[i]).Replace("-", answer);
                            temp = temp.Substring(0, i) + lalagyan + temp.Substring(i + 1, temp.Length - i + 1);
                        }
                    }
                    else
                    {
                        if (!bol)
                        {
                            temp += "-";
                        }
                    }
                }
                bol = true;
                Console.Write(temp);
            }
            while (count < 5);
            Console.Write("\nEnter Your Final Guess: ");
            answer = Console.ReadLine();
            answer = answer.ToUpper();
            if (answer.Equals(index))
            {
                Console.WriteLine("\nYour Guess Is Correct!");
            }
            else
            {
                Console.WriteLine("\nYour Guess Is Wrong!");
            }
        }
    }
}

输出:

---
Enter a letter
Remaining Chances: 5
Clue: the word is 3 letters
Answer: o

 --o
Enter a letter
Remaining Chances: 4
Clue: the word is 3 letters
Answer: t

Correct Letter
t --o
Enter a letter
Remaining Chances: 3
Clue: the word is 3 letters
Answer: w

Correct Letter
tw--o
Enter a letter
Remaining Chances: 2
Clue: the word is 3 letters
Answer: o

Correct Letter
two-o
Enter a letter
Remaining Chances: 1
Clue: the word is 3 letters
Answer: o

Correct Letter
two-o
Enter Your Final Guess: two

Your Guess Is Wrong!

【问题讨论】:

  • 你给temp.Substring()打了两次电话。哪个抛出异常?将它们分解为单独的操作并调试以找出答案。抛出异常时,temp 的确切值是多少? i 的确切值是多少?
  • temp.Substring(i + 1, temp.Length) 几乎肯定是错误的。注意第二个参数是你要提取的字符数,所以可能你的意思是temp.Substring(i + 1, temp.Length - i - ))

标签: c# substring


【解决方案1】:

ArgumentOutOfRange 异常通常意味着您正在尝试获取超出数组/集合边界的值。

在您的情况下,如果用户猜测最后一个字母,则 i 值如下:

temp = temp.Substring(0, i) + lalagyan + temp.Substring(i + 1, temp.Length);

第一个temp.Substring(0,i) 将返回整个临时字符串,第二个temp.Substring(i+1, temp.Length) 将尝试从最后一个索引开始返回一个长度为temp.Length 的字符串 - 因为这是不可能的,它可能会导致异常。

查看这行代码应该做什么。

【讨论】:

    【解决方案2】:

    Substring 中的第二个参数是子字符串的长度,这就是为什么

      temp.Substring(i + 1, temp.Length)
    

    是错误的:temp.Length整个 字符串的长度,这就是它对于子字符串而言 太大 的原因。你可以把它写成

      temp = temp.Substring(0, i) + lalagyan + temp.Substring(i + 1);
    

    这里temp.Substring(i + 1) 的意思是“从i + 1 开始,直到结束”。

    编辑:如果是任意i,您也应该检查i

      temp = 
          i <= 0 ? lalagyan + temp 
        : i >= temp.Length ? temp + lalagyan
        : temp.Substring(0, i) + lalagyan + temp.Substring(i + 1);
    

    【讨论】:

    • 请注意,如果i + 1 已经是&gt;= temp.Length 你也会得到异常
    猜你喜欢
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 2021-05-21
    • 2015-03-08
    • 2019-08-14
    相关资源
    最近更新 更多