while (true)
{
//read in the file
StreamReader convert = new StreamReader("../../convert.txt");
//define variables
string line = convert.ReadLine();
double conversion;
int numberIn;
double conversionFactor;
//ask for the conversion information
Console.WriteLine("Enter the conversion in the form (Amount, Convert from, Convert to)");
String inputMeasurement = Console.ReadLine();
string[] inputMeasurementArray = inputMeasurement.Split(',');
//loop through the lines looking for a match
while (line != null)
{
string[] fileMeasurementArray = line.Split(',');
if (fileMeasurementArray[0] == inputMeasurementArray[1])
{
if (fileMeasurementArray[1] == inputMeasurementArray[2])
{
Console.WriteLine("The conversion factor for {0} to {1} is {2}", inputMeasurementArray[1], inputMeasurementArray[2], fileMeasurementArray[2]);
//convert to int
numberIn = Convert.ToInt32(inputMeasurementArray[0]);
conversionFactor = Convert.ToDouble(fileMeasurementArray[2]);
conversion = (numberIn * conversionFactor);
Console.WriteLine("{0} {1} is {2} {3} \n", inputMeasurementArray[0], inputMeasurementArray[1], conversion, inputMeasurementArray[2]);
break;
}
}
else
{
Console.WriteLine("Please enter two valid conversion types \n");
break;
}
line = convert.ReadLine();
}
}
The file consists of the following:
ounce,gram,28.0
pound,ounce,16.0
pound,kilogram,0.454
pint,litre,0.568
inch,centimetre,2.5
mile,inch,63360.0
The user will input something like 6,ounce,gram
The idea is that it finds the correct line by checking if the first and second words in the file are the same as the second and third the user enters.
The problem is that if it checks the first line and it fails the if statement, if goes through to the else statement and stops. I am trying to find a way where it will stop after the it finds the correct line but not until. If someone types in a value that isn’t in the file, then it should show an error.
Remove the break statement in the else clause. That’s causing it to exit the loop.
You could really improve this code by reading the conversion factors into an internal data structure, perhaps a dictionary keyed by the “from” conversion unit with the value be a dictionary of possible output units and their conversion factor — or a custom key/value pair if you only have a single possible output unit. This would turn your inner loop into a two-stage look up (much faster) and save you the trouble of having to re-read the conversion file each time. As @Ben points out, the error message is in the wrong place, too. It needs to be outside the loop/lookup, and only executed if no match was found.
Sample code — note there is no input validation in this code: