我正在创建一个自定义方法,该方法返回AnalyzerInts[]
来计算string input
的小写,大写,空格,标点符号和字符数。我得到一个未处理的异常错误。 “System.IndexOutOfRangeException:索引超出了数组的范围。”我如何正确检索我的Int[] AnalyzerInts
值到我的主要方法?从自定义字符串方法返回一个Int数组?
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a string/sentence: ");
string userInput = Console.ReadLine();
int[] answers = StringAnalyzer(userInput);
Console.WriteLine("You have {0} uppercase letters in your string.", answers[0]);
Console.WriteLine("You have {0} lowercase letters in your string.", answers[1]);
Console.WriteLine("You have {0} whitespace characters in your string.", answers[2]);
Console.WriteLine("You have {0} punctuation characters in your string.", answers[3]);
Console.WriteLine("You have {0} characters in your string.", answers[4]);
}
static int[] StringAnalyzer (string input)
{
int[] AnalyzerInts = new int[4];
for (int x = 0; x < input.Length; x++)
{
if (char.IsUpper(input[x]))
{
AnalyzerInts[0]++;
}
else if (char.IsLower(input[x]))
{
AnalyzerInts[1]++;
}
else if (char.IsWhiteSpace(input[x]))
{
AnalyzerInts[2]++;
}
else if (char.IsPunctuation(input[x]))
{
AnalyzerInts[3]++;
}
AnalyzerInts[4]++;
}
return AnalyzerInts;
}
它引发错误,因为您声明函数返回字符串,但尝试返回“ INT []'。如果函数应该返回,则将返回类型更改为“int []”。 –
这是否甚至编译?我从来没有见过类似'return AnalyzerInts [];'的代码,我也不会期望。 –
直到我正确地将我的方法签名更改为'static int [] StringAnalyzer(string input)''它才编译。现在我只是试图正确地将我的'AnalyzerInts;'值返回到我的主方法而不会出现错误。 –