请有人帮忙吗?我需要创建一个程序,读取单位列表和名称“例如盎司,克,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();
}
}
}
答案 0 :(得分: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是一个肯定的迹象,你写了一个糟糕的算法 - 他们是非常有用的......