我想要做的是,在这个人输入他们的名字之后,询问他们是否愿意再次这样做,如果没有,请点击n,然后退出程序。但我似乎无法让它发挥作用。我试过添加一个退出案例,但仍然没有。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestApp
{
class Program
{
static void Main()
{
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
Test(name.ToLower());
Console.ReadLine();
}
static void Test(string name)
{
bool exit = true;
string answer = "";
do
{
switch (name)
{
case "name":
Console.WriteLine("Hello Name");
break;
case "name2":
Console.WriteLine("Hello Name2");
break;
}
Console.WriteLine("Would you like to enter a new name? y/n: ");
if (answer == "y")
exit = false;
else
exit = true;
}
while (exit == false);
}
}
}
答案 0 :(得分:2)
您没有在循环中更改'answer'变量。你在循环中缺少一个Console.ReadLine()。
Console.Write("Would you like to enter a new name? y/n: ");
answer = Console.ReadLine(); <----------- this was missing
exit = (answer == "y" || answer == "Y"); <------- this slight improvement
此外,您应该读取循环内部的名称,因为当exit为false时您想要再次读取它。现在你一遍又一遍地检查同一个名字。
static void Test() <---- remove the name parameter
{
bool exit = true;
string answer = "";
do
{
Console.Write("Please enter your name: ");
string name = Console.ReadLine().ToLower(); <--- read name here
答案 1 :(得分:1)
answer = Console.ReadLine(); //你的代码中缺少这一行。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestApp
{
class Program
{
static void Main()
{
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
Test(name.ToLower());
Console.ReadLine();
}
static void Test(string name)
{
bool exit = true;
string answer = "";
do
{
switch (name)
{
case "name":
Console.WriteLine("Hello Name");
break;
case "name2":
Console.WriteLine("Hello Name2");
break;
}
Console.WriteLine("Would you like to enter a new name? y/n: ");
answer = Console.ReadLine(); // you're missing this line in your code.
if (answer == "y")
exit = false;
else
exit = true;
}
while (exit == false);
}
}
}
答案 2 :(得分:0)
结合Hasan和Harsh提出的观点,这里有一个似乎可以做你想要的工作样本。
static void Test()
{
bool exit = true;
string answer = "";
do
{
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
switch (name)
{
case "name":
Console.WriteLine("Hello Name");
break;
case "name2":
Console.WriteLine("Hello Name2");
break;
}
Console.WriteLine("Would you like to enter a new name? y/n: ");
answer = Console.ReadLine();
if (answer == "y")
exit = false;
else
exit = true;
}
while (!exit);
}
当然,如果你输入一个不是“name1”或“name2”的名字,那么事情就会开始变得怪异,因为在这种情况下你还没有真正定义你想要发生的事情。但希望这会让你有一个良好的开端。