【发布时间】:2019-08-06 01:20:31
【问题描述】:
我是编码的初学者 - 我一周前才开始。我正在尝试开发一个程序,用户可以在其中查看列表中的所有名称或将名称添加到列表中。当用户提示查看列表中的姓名,然后决定采取另一项操作时,他们会陷入无限循环,只能再次看到这些姓名。我希望他们能够回到起点并选择查看名称或添加名称。
我已经尝试重新组织和查找内容,但我仍然不知所措。
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> names = new List<string>();
names.Add("Vasti");
names.Add("Cameron");
names.Add("Ezra");
names.Add("Tilly");
bool program = false;
bool program2 = false;
Console.WriteLine("Welcome to the names lost! If you wish to add
a name to the list, type 1. If you want to see current names in
the list,
type 2.");
string userChoice = Console.ReadLine();
do
{
switch (userChoice)
{
case "1":
Console.WriteLine("Add a name to the squad.");
string userAddName = Console.ReadLine();
names.Add(userAddName);
break;
case "2":
Console.WriteLine("Here's the list:");
foreach (string name in names)
{
Console.WriteLine(name);
}
Console.WriteLine("Wanna do that again? Type yes or
no.");
do
{
string userContinue = Console.ReadLine();
switch (userContinue)
{
case "yes":
program = true;
program2 = false;
break;
case "Yes":
program = true;
program2 = false;
break;
case "no":
program = false;
program2 = false;
break;
case "No":
program = false;
program2 = false;
break;
default:
Console.WriteLine("Please enter either
yes or no");
userContinue = Console.ReadLine();
program2 = true;
break;
}
}
while (program2 == true);
break;
default:
Console.WriteLine("Please type either 1 or 2 to
select an option.");
break;
}
}
while (program == true);
}
}
我希望用户返回到开始的提示,但他们一遍又一遍地停留在同一个提示中。没有错误消息。
【问题讨论】:
-
这段代码有很多问题。 1. 考虑到每个部分处理不同的功能,loop-in-a-switch-statement-in-a-loop 有点过于嵌套。我可能会将事情分解成单独的方法。例如,“AddName”和“ListSquad”。 2. 变量名有点模棱两可(
program是什么?你的整个应用程序就是一个程序)。 3. "userChoice" 唯一更新的地方是列表小队的内部循环。 4. 现在,在你为小队添加一个名字之后,就是这样,你退出主循环。 5. 你应该看看如何进行不区分大小写的匹配与是/是等。
标签: c# loops switch-statement