我有下面的代码,它应该要求用户输入由#(如1#2#3##2等)分隔的各种整数。然后应该找到输入序列中具有重复的值并将其显示为“序列包含 2 个重复值”。
但是,我不确定用于分隔用户输入值的代码是否正确,因为它显示错误:
public class Program
{
public static void Main(string[] args)
{
// Keep the following line intact
Console.WriteLine("===========================");
// Insert your solution here.
// user input gets the input from the user
// regarding a line where integers are separated by #
String userInput;
Console.WriteLine("Please enter single line containing a list of integers, separated by '#':");
userInput = Console.ReadLine();
// splitting the userInput into Array of Strings
if (userInput != null)
{
// splitting the userInput by #
String[] numberStrings = userInput.Split("#");
// numbers list contain the list of unique numbers
List<int> numbers = new List<int>();
// takes count of duplicate numbers
int totalDuplicateNumbers = 0;
// adding the number string to the list after converting to int
for (int i = 0; i < numberStrings.Length; i++)
{
numbers.Add(Int32.Parse(numberStrings[i]));
}
// now sorting the number list
numbers.Sort();
bool duplicatePresent = false;
for (int i = 0; i < numbers.Count - 1; i++)
{
if (numbers[i] == numbers[i + 1])
{
if (!duplicatePresent)
{
duplicatePresent = true;
totalDuplicateNumbers += 1;
}
}
else
{
duplicatePresent = false;
}
}
// display result
Console.WriteLine($"The sequence contains {totalDuplicateNumbers} repeated values.");
}
else
{
Console.WriteLine("Wrong input");
}
// Keep the following lines intact
Console.WriteLine("===========================");
}
}
Run Code Online (Sandbox Code Playgroud)
您的代码不正确。Split需要一个或多个字符来分割。你传递了一个字符串。传递一个字符,如下所示:
String[] numberStrings = userInput.Split('#');
Run Code Online (Sandbox Code Playgroud)
请注意,此解决方案将在您的测试输入上失败
1#2#3##2
因为这意味着存在这些字符串"1", "2", "3", "", "2",并且""在您后续的解析尝试中将失败。
你可能想尝试
String[] numberStrings = userInput.Split('#', StringSplitOptions.RemoveEmptyEntries);
Run Code Online (Sandbox Code Playgroud)
这将删除空的非数字条目。这是否是你的练习想要你做的事情,或者你是否应该用空输入做其他事情,只有你才能回答。
| 归档时间: |
|
| 查看次数: |
114 次 |
| 最近记录: |