簡體   English   中英

.txt文件的C#單位轉換

[英]c# unit conversion from .txt file

請有人幫忙嗎? 我需要創建一個程序,該程序讀取單位和名稱“例如盎司,克,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();
}
}

}

對於初學者來說,每次用戶想要結果時,您似乎都在閱讀文本文件,並且只有第一行!

讀入文本文件並將其內容保存在某處,將轉換因子保存在Dictionary中:

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是確定您編寫的算法較差的肯定信號-嗯,它們很少有用...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM