[英]Argument OutofRange Exception was unhandled
我的代碼說了一個字,它可以工作,但顯示此錯誤:
未處理參數OutofRange異常
正在顯示錯誤行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.Substring,這是無效的參數。 將您的while
條件更改為while( intWordLength > 0 )
。
這樣的事情可能會起作用:
while (intWordLength != -1)
{
if (intWordLength == 0)
{
break;
}
strFlippedWord = strUserWord.Substring(intWordLength - 1, 1);
System.Console.Write(strFlippedWord);
intWordLength -= 1;
}
您從字符串的最后一個字符開始,向前移動1個元素
嘗試:
strFlippedWord = strUserWord.Substring(intWordLength - 1, 0);
如果您想反轉字符串
strFlippedWord = new string(strUserWord.Reverse().ToArray());
編輯
如babak關於intwordlength所述:
而while語句可能是
while(!(intwordlength < 1) )
當intWordLength為0時,Substring會引發您看到的異常。
http://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx
在這種情況下,您傳遞的是-1,這是不合法的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.