namespace StringProgramFruits
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("What is your favourite fruit?, (Apples), (Bananas), (Kiwi) or (Peaches)?");
string fruit = Console.ReadLine();
if (fruit == "Apple")
{
Console.WriteLine("Apples!");
}
if (fruit == "Kiwi")
{
Console.WriteLine("Kiwi!");
}
if (fruit == "Bananas")
{
Console.WriteLine("Bananas!");
}
while (fruit != "Apple") while (fruit != "Bananas") while (fruit != "Kiwi")
{
Console.WriteLine("Try Again!");
fruit = Console.ReadLine();
if (fruit == "Apple")
{
Console.WriteLine("Apples!");
}
if (fruit == "Kiwi")
{
Console.WriteLine("Kiwi!");
}
if (fruit == "Bananas")
{
Console.WriteLine("Bananas!");
}
return;
}
}
}
如果你看那里的while循环,我只需在一行中添加3个函数来添加更多条件。这在代码库中看起来并不是很好,所以我想知道是否有一种不同的或更简单的方法来为while循环添加多个条件。我尝试过使用
while (fruit != "Apple") || (fruit != "Bananas") || (fruit != "Kiwi")
但上面的代码只显示为无效的表达式:/
很可能很明显我对C-sharp很新,虽然这是一个非常微不足道的问题,但我仍然想知道是否还有其他方法。
编辑:我现在才意识到我需要放置&&&'在while函数之间,但只是通过查看重构,真正展示了如何始终缩短和改进代码(使用switch,dictionaries等)以及我对基础知识的了解甚少。答案 0 :(得分:1)
试试这个代码我重构
static void Main(string[] args)
{
Console.WriteLine("What is your favourite fruit?, (Apples), (Bananas), (Kiwi) or (Peaches)?");
string[] words = new string[] { "Apple", "Bananas", "Kiwi" };
string input = Console.ReadLine();
while (!words.Contains(input))
{
Console.WriteLine("Try Again!");
input = Console.ReadLine();
}
Console.WriteLine(input + "!");
}
答案 1 :(得分:0)
我认为您正在寻找在用户的回答不是Apple,Bananas或Kiwi的情况下运行的声明,所以:
build
答案 2 :(得分:0)
我做了一个不重复水果列表的重构。此外,它看起来像复数中的一些不一致,单数。我把它们都变成了单数。使用HashSet可以很容易地进行不区分大小写的检查。
HashSet<string> validFruits = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase)
{ "Apple", "Banana", "Kiwi", "Peach" };
Console.WriteLine($"What is your favourite fruit? {string.Join(", ", validFruits.Select(f => $"({f})"))}");
string fruit = Console.ReadLine();
while (!validFruits.Contains(fruit))
{
Console.WriteLine("Try Again!");
fruit = Console.ReadLine();
}
Console.WriteLine($"{fruit}!");
答案 3 :(得分:0)
这是A.Gupta提供的简化版本:
static void Main(string[] args)
{
Console.WriteLine("What is your favourite fruit?, (Apples), (Bananas), (Kiwi) or (Peaches)?");
string[] words = { "Apples", "Bananas", "Kiwi", "Peaches" }; // simple array declaration
string input = Console.ReadLine();
while (!words.Contains(input))
{
Console.WriteLine("Try Again!");
input = Console.ReadLine();
}
Console.WriteLine(input + "!");
Console.ReadKey(); // optional to let the User read the response
}
致以最诚挚的问候,