我正在尝试创建一个多功能程序。对于一个部分,数组用随机数填充。然后用户输入一个数字,程序返回数字出现在数组中的位置。它还返回数字在数组中出现的次数。
然而,它只执行一次,然后结束程序。我希望它提示用户输入一个数字进行搜索,直到用户按下按钮为止,例如说'P'。一旦用户在显示结果后按“P”,程序应该关闭。我应该使用哪些方法或功能的任何提示?
这是我的代码的细分版本。
Console.Write("Now enter a number to compare: ");
int c = Convert.ToInt32(Console.ReadLine());
for (int j = 0; j < arr.Length; j++)
{
if (arr[j] == c)
{
pos.Add(j);
}
}
if (pos.Count == 0)
{
Console.WriteLine("Sorry this number does not match");
}
else
{
Console.WriteLine("The number {0} appears {1} time(s)",c,pos.Count);
}
Console.ReadLine();
答案 0 :(得分:0)
这应该会给你一点启动
您必须在代码周围使用循环并检查要退出的关键字
class Program
{
static void Main(string[] args)
{
var arr = new int[50];
var pos = new List<int>();
string result;
do
{
Console.Write("Now enter a number to compare: ");
result = Console.ReadLine();
int c;
if (int.TryParse(result, out c))
{
for (int j = 0; j < arr.Length; j++)
{
if (arr[j] == c)
{
pos.Add(j);
}
}
if (pos.Count == 0)
{
Console.WriteLine("Sorry this number does not match");
}
else
{
Console.WriteLine("The number {0} appears {1} time(s)", c, pos.Count);
}
}
} while (result != "exit");
}
}
答案 1 :(得分:0)
我将提供另一种方法,虽然没有测试下面的代码。
class Program
{
//declare your class variables here
//so that you can access them from the methods and do your operations
bool Up=true;
static void Main(string[] args)
{
Console.WriteLine("Program started.");
ThreadPool.QueueUserWorkItem(ConsoleCommands);
while (Up)
{
Thread.Sleep(2000);
}
Console.WriteLine("Program ended.");
}
private static void ConsoleCommands(object dummy)
{
while (Up)
{
string cmd = ConsoleReceiver().ToLower();
switch (cmd)
{
case "exit":
Up=false;
break;
//implement more cases here and fill the rest of your business
//example:
case "1":
if (pos.Count == Int32.Parse(cmd))//just a dummy business
{
Console.WriteLine("Sorry this number does not match");
}
else//another dummy business
{
Console.WriteLine("Sth...");
}
break;
default:
Console.WriteLine("Unrecognized command");
break;
}//or forget about switch and use if-else stements instead.
}
}
private static string ConsoleReceiver()
{
Console.WriteLine("#cmd:");
return Console.ReadLine();
}
}
答案 2 :(得分:0)
如果你想明确阅读单键笔画......
ConsoleKeyInfo keyInfo;
do {
Console.Write("Enter a number to compare; press the 'p' key to quit: ");
keyInfo = Console.ReadKey(false);
int c;
if (Int32.TryParse(keyInfo.KeyChar.ToString(), out c))
{
for (int j = 0; j < arr.Length; j++)
{
if (arr[j] == c)
{
pos.Add(j);
}
}
if (pos.Count == 0)
{
Console.WriteLine("Sorry this number does not match");
}
else
{
Console.WriteLine("The number {0} appears {1} time(s)",c,pos.Count);
}
} while (keyInfo.Key != ConsoleKey.P)
否则,您可以通过@Fredou和我发布的内容的组合获得创意。
答案 3 :(得分:-1)
试试这个:)
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
start:
string tryagain;
//All of your Code Goes here
tryagain = Console.ReadLine();
if (tryagain != "p")
{
goto start;
}
else
{
Environment.Exit(0);
}
}
}
}