【问题标题】:c# unit conversion from .txt filec# .txt 文件的单位转换
【发布时间】:2011-07-22 15:30:21
【问题描述】:

请问有人可以帮忙吗?我需要创建一个程序来读取单位和名称列表“例如盎司,克,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();
}
}

}

【问题讨论】:

  • 这绝对是功课。
  • 既然输入格式是CSV?为什么不使用 CSV 阅读器?
  • blinks 你用的是goto?? :)
  • yup goto 让我立即认为这是家庭作业。
  • 希望您的 CSV 文件不包含 val1, "Uh,Oh", val2 之类的内容。是的,解析 CSV 文件并不像拆分字符串那么简单。

标签: c# units-of-measurement


【解决方案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 肯定表明你编写了一个糟糕的算法 - 它们很少有用......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 2013-12-24
    • 2013-10-22
    • 2018-11-05
    • 2019-08-29
    • 2016-10-02
    • 2015-12-11
    相关资源
    最近更新 更多