0

请问有人可以帮忙吗?我需要创建一个程序来读取单位和名称列表“例如盎司,克,28”,然后要求用户输入,然后转换并显示结果。到目前为止,我所能做的就是让它阅读第一行,但没有别的。

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Soft140AssPt3V2
{
class Program
{
static void Main(string[] args)
{
Main:
string line, Start, Finish, j, l;
double Factor, Output, Amount;
string[] SplitData = new string [2];
StreamReader Units = new StreamReader("../../convert.txt");
while ((line = Units.ReadLine()) != null)
{
SplitData = line.Split(',');
Start = SplitData[0];
Finish = SplitData[1];
Factor = Convert.ToDouble(SplitData[2]);


//Get inputs
Console.WriteLine("Please input the amount, to and from type (Ex. 5,ounces,grams):");
string Input = Console.ReadLine();
string[] Measurements = Input.Split(',', ' ', '/', '.');
Amount = Convert.ToDouble(Measurements[0]);
j = Measurements[1];
l = Measurements[2];

if (j == Start)
{
Output = (Factor * Amount);
Console.WriteLine("{0} {1} equals {2} {3}", Amount, Measurements[1], Output, Measurements[2]);
Console.ReadLine();
goto Main;
}

else
{

}

}
Units.Close();
}
}

}
4

1 回答 1

1

对于初学者来说,每次用户想要结果时,您似乎都在读取文本文件,而且只有第一行!

读入文本文件并将其内容保存在某处,将转换因子保存在字典中:

Dictionary<string, double> convFactors = new Dictionaty<string, double>();
while ((line = Units.ReadLine()) != null)
{
    SplitData = line.Split(',');
    string from = SplitData[0];  // should really be named 'from' not STart
    string to = SplitData[1]; // should really be named 'to' not Finish
    double factor = Convert.ToDouble(SplitData[2]); // or double.Parse ??
    convFactors.Add( from + "-" + to , factor); // ie: stores "ounce-gram", 28.0
}

现在循环从控制台读取输入并回答问题:

while (true);
{
    Console.WriteLine("Please input the amount, to and from type (Ex. 5,ounces,grams):");
    string Input = Console.ReadLine();
    if (Input.Equals("quit") || Input.Length == 0)
        break;
    string[] tk = Input.Split(',', ' ', '/', '.');

    double result = convFactors[tk[1] + "-" + tk[2]] * double.Parse(tk[0]);
    Console.WriteLine("{0} {1} equals {2} {3}", tk[0], tk[1], result, th[2]);
    Console.ReadLine();  // is this readline really needed??
}

编辑:是的 - 忘记 goto 甚至在语言中......使用 goto 肯定表明你编写了一个糟糕的算法 - 它们很少有用......

于 2011-03-25T04:36:06.473 回答