参数超出范围异常未处理

本文关键字:异常 未处理 范围 参数 | 更新日期: 2023-09-27 17:51:13

我的代码翻转一个单词,它工作,但显示这个错误:

参数outorange异常未处理

strFlippedWord = strUserWord.Sub...

行显示错误
string strUserWord;
string strFlippedWord;
int intWordLength;
System.Console.WriteLine("Please enter a word to flip: ");
strUserWord = System.Console.ReadLine();
intWordLength = strUserWord.Length;
while (intWordLength != -1)
{
    strFlippedWord = strUserWord.Substring(intWordLength - 1, 1); 
    System.Console.Write(strFlippedWord);
    intWordLength -= 1;
}
System.Console.ReadKey();

参数超出范围异常未处理

你的循环运行时间太长了。

while (intWordLength > 0)

同样,您可以完全消除循环并使用一点LINQ:

Console.WriteLine(strUserWord.Reverse().ToArray());

intWordLength为0时,将-1作为第一个参数传递给String。子字符串,这是一个无效参数。将while条件更改为while( intWordLength > 0 )

可以这样做:

while (intWordLength != -1)
{
    if (intWordLength == 0)
    {
        break;
    }
    strFlippedWord = strUserWord.Substring(intWordLength - 1, 1);
    System.Console.Write(strFlippedWord);
    intWordLength -= 1;
 }

当intWordLength为0时,Substring抛出您所看到的异常。

http://msdn.microsoft.com/en-us/library/aka44szs (v = vs.110) . aspx

在这种情况下,您传递的是-1,这是不合法的

从字符串的最后一个字符开始,向前移动1个元素

试题:

strFlippedWord = strUserWord.Substring(intWordLength - 1, 0);

如果你试图反转字符串

strFlippedWord = new string(strUserWord.Reverse().ToArray());

编辑

正如babak所说的inwordlength:

while语句可以是

while(!(intwordlength < 1) )