【发布时间】:2011-09-29 00:55:46
【问题描述】:
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;
namespace ConsoleApplication9
{
class main
{
private static StreamWriter objWriter = new StreamWriter(@"D:\text1.txt", true);
private static StreamWriter tripWriter = new StreamWriter(@"D:\text2.txt", true);
private static void Main()
{
WelcomeMenu();
}
public static void WelcomeMenu()
{
Console.WriteLine("Welcome to Pow Drop Log v1");
Console.WriteLine("A. Press A to start the trip");
while (true)
{
string enteredWelcome = Console.ReadLine();
{
if (enteredWelcome == "a")
{
List();
}
else
{
Console.WriteLine("That is an invalid option");
continue;
}
}
}
}
public static void WriteToTextFile(string text)
{
objWriter.Write(text);
objWriter.Flush();
}
public static void WriteToCurrentTrip(string text)
{
tripWriter.Write(text);
tripWriter.Flush();
}
public static void List()
{
Stopwatch Triptime = new Stopwatch();
Triptime.Start();
Console.WriteLine("You have started the trip");
Dictionary<string, string> tdItems = new Dictionary<string, string>();
tdItems.Add("1", "foo");
tdItems.Add("2", "bar");
tdItems.Add("3", "bar");
tdItems.Add("4", "end");
while (true)
{
string[] items = Console.ReadLine().Split(' ');
string result = null;
int result1;
TimeSpan timeSpan = Triptime.Elapsed; string time = string.Format("{0:00}:{1:00}:{2:00}", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);
foreach (string itemNumber in items)
{
if (tdItems.ContainsKey(itemNumber) && (int.TryParse(itemNumber, out result1)))
{
result += " + " + tdItems[itemNumber];
WriteToTextFile(tdItems[itemNumber] + Environment.NewLine);
WriteToCurrentTrip(tdItems[itemNumber] + Environment.NewLine);
}
if (!tdItems.ContainsKey(itemNumber) && (int.TryParse(itemNumber, out result1)))
{
Console.WriteLine("You have entered a drop which is not in the database, Try again");
continue;
}
else if (itemNumber == "end")
{
Triptime.Stop();
Console.WriteLine("End of Trip");
Console.WriteLine("Elapsed time " + time);
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("");
WelcomeMenu();
break;
}
}
}
}
}
}
代码似乎是遍历每个部分而不是一次。
假设我在控制台中输入 1 2 3,它会在文本文件中写入
富 富吧 富吧巴兹 而不是一开始就写 foo + bar + baz。
我调试了它,它显示它一直在运行,我该如何解决这个问题并让它正确运行?
谢谢!
【问题讨论】:
-
如果不进行重大更改就无法运行它,很难判断发生了什么。请把它转换成一个简短但完整的程序,我们可以编译和运行。
-
@Jon Skeet - 使用完整代码对其进行了编辑。抱歉,如果它真的很混乱,错误和错误的流程等,我才一个半星期前开始。
标签: c# loops dictionary foreach