问题
using System;
class Program
{
static void Main(string[] args)
{
string candidateName = Console.ReadLine();
string input = Console.ReadLine();
int numberOfAdmittedPersons = Convert.ToInt32(input);
string result = string.Empty;
for (int i = 1; i <= numberOfAdmittedPersons; i++)
{
string listOfAllAdmittedPersons = Console.ReadLine();
{
if (i != numberOfAdmittedPersons)
{
result += listOfAllAdmittedPersons;
}
}
}
if (result.Contains(candidateName))
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false");
}
}
}
The application receives on the first line the name of a candidate C (inputted by the user). The next line contains the number of persons admitted (also inputted by the user).Then the list of all admitted persons follows, one person per line (also inputted by the user).
I have to make an application which displays "True" if candidate C was admitted (C is found in the list) or "False" if the candidate was rejected (C is not on the list) for example : if I input :
John
3
George
Maria
John
The console will display : true
But the result I get is : false
.
What can I do to correct my code?
回答1:
Another way is to define a list to store the names.
List<string> result = new List<string>();
for (int i = 0; i < numberOfAdmittedPersons; i++)
{
// add items
result.Add(Console.ReadLine());
}
if (result.Contains(candidateName))
{
// ...
}
回答2:
Your code has a couple of issues. What is causing your bug is this line:
if (i != numberOfAdmittedPersons)
It means the last name is not being added to your string.
However there is another problem. Given the following input:
MAX
2
AMA
XAVIER
The result would be true
as the string AMAXAVIER
contains the string MAX
. The answer is to use a collection, for example:
string[] result = new string[numberOfAdmittedPersons];
for (int i = 0; i < numberOfAdmittedPersons; i++)
{
result[i] = Console.ReadLine();
}
if (result.Contains(candidateName))
{
...
来源:https://stackoverflow.com/questions/65810480/a-problem-that-i-tried-to-solve-with-the-help-of-strings-and-repetitive-instruct