我是一所大学的一年级学生,专注于自我学习(SCRUM),没有任何经典课程。正因为如此,我从这样的网站上学到了我所知道的一切。我不想有任何坏习惯或错误的理解。那么,这段代码有用吗?我并不是在寻找优化(不过,我不介意任何技巧),因为我将通过时间来学习这一点,但是如果总体结构和我的思维方式是正确的话。
static void Main(string[] args)
{
string repeat;
//do while loop for if the user wants to run the program again
do
{
//asigns variables
string text;
int vowels, consonants, numbers, otherSymbols;
var hsVowels = new HashSet<char> { 'a', 'e', 'i', 'o', 'u' };
var hsConsonants = new HashSet<char> { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'};
var hsNumbers = new HashSet<char> { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
//asks for input
Console.WriteLine("Input anything and the program wil tell you how many vowels, consonants, numbers and other symbols you gave.");
text = Console.ReadLine().ToLower();
//calculates
vowels = text.Count(c => hsVowels.Contains(c));
consonants = text.Count(c => hsConsonants.Contains(c));
numbers = text.Count(c => hsNumbers.Contains(c));
otherSymbols = text.Length - (vowels + consonants + numbers);
//shows the result
Console.WriteLine("Your input has {0} vowels, {1} consonants, {2} numbers and {3} other Symbols.", vowels, consonants, numbers, otherSymbols);
//asks if the user wants to run the program again
Console.WriteLine("Would you like to try again? (yes/no)");
repeat = Console.ReadLine();
//tests if the users input was valid (yes/no)
while (!(repeat.ToLower().Contains("yes") || repeat.ToLower().Contains("no")))
{
Console.WriteLine(@"Invalid input. Please answer ""yes"" or ""no"" .");
repeat = Console.ReadLine();
}
} while (repeat.ToLower().Contains("yes"));
}我不知怎么没能让代码示例将我的代码识别为C#。如果有人能告诉我怎么做的话,我会非常感激的!
发布于 2018-11-17 10:43:27
我已经测试过这段代码了,它还能工作。干得好:-)
正如自带所暗示的,在建议的站点上张贴可能是个好主意。
尽管如此,以下是我对您的代码所做的一些更改,以提高代码的可读性,并减少一些重复:
在进入循环之前,使用while循环并设置条件变量。您至少要做一个循环:
string repeat = "yes";
//Main loop
while (repeat.Contains("yes")) 一行变量声明。我个人不建议这样做。通过在单行中声明一个变量,可以更容易地阅读:
string inputText;
int howManyVowels;
int howManyConsonants;
int howManynumbers;
int howManySymbols;从上面你可以看到,我试图尽可能明确我的命名。命名时不要害怕冗长。一个命名良好的变量是不言自明的,并显示了意愿。
变量的使用。关于这件事有很多种意见。在编写好的代码时,我个人认为必须尽可能少地使用var。在这种情况下是可以的,因为右手边是不言自明的。然而,最好是显示左手侧的类型。
List<char> listOfVowels = new List<char> { 'a', 'e', 'i', 'o', 'u' };这只是我的偏好。使用List代替HashSet。由于我们并不真正关心性能--在这种情况下-- List的使用突出了这样一个事实:我们正在处理一个char列表。
最后一点,如果您需要检查小写的响应,那么在初始化它时设置ToLower()变量:
repeat = Console.ReadLine().ToLower()希望能帮上忙。
https://stackoverflow.com/questions/53350128
复制相似问题