【发布时间】: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 - ))