Could anyone help with the code I have made. The problem is that it is reading in the conversion txt file but because there is a space between some of the data it will not display the result, it comes up with a message saying 'out of bounds of the array'. The idea of the code is that it uses the file to convert a users input. Ex. 5,ounce,gram this would display a result like 5 ounces is equal to 141 grams. But for example it won't display the result for 1,mile,inch because of the space. I also cannot change the txt file. Cheers.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;


namespace Final_version_2
{
    class Program
    {
        static void Main(string[] args)
        {
            string line, To, From, j, l, lineTotal = "";// These are the strings for the program, which includes the line total to count the amount of lines in the text file.
            double Factor, Output, Amount; //These are the double varibles which will be floating point number varibles.
            string[] SplitData = new string[2];// This is setting up the array for the program.
            string[] fileLn; // This is another srting called fileLn.
            StreamReader Units = new StreamReader(@"..convert.txt"); // This is file path to find the convert.txt file.
            while ((line = Units.ReadLine()) != null) // This is the start of the while loop.
            {
                lineTotal += line + "\n"; // This is count the total amount of lines in txt file.
            }
            fileLn = lineTotal.Split('\n'); //This places the file lines in an array of string.
            Main:
            //This is getting the inputs from the user.
            Console.WriteLine("Please input the amount, to and from type (Ex. 5,ounces,grams):"); // This is displayed on the console for the user to read.
            string Input = Console.ReadLine(); // This puts the inputs as strings.
            for (int i = 0; i < fileLn.Length - 1; i++)
            {
                SplitData = fileLn[i].Split(',');
                To = SplitData[0];
                From = SplitData[1];
                Factor = Convert.ToDouble(SplitData[2]);
                Console.WriteLine(To + " - " + From + " - " + Factor + " - ");
                string[] Measurements = Input.Split(',', ' ', '/', '.');
                Amount = Convert.ToDouble(Measurements[0]);
                j = Measurements[1];
                l = Measurements[2];
                if (j == To)
                {
                    Output = (Factor * Amount);
                    Console.WriteLine("{0} {1} is equal to {2} {3}", Amount, Measurements[1], Output, Measurements[2]);
                    Console.ReadLine();
                    goto Main;
                    //break;
                }
                else
                {
                   // Console.WriteLine("Not Matched");
                   // Console.ReadLine();
                }
            }
            Units.Close();
        }
    }
}

Recommended Answers

All 12 Replies

It's pretty hard to find the error without a sample of the data in the text file.

ounce,gram,28.3495
pound,ounce,16.0
pound,kilogram,0.453592
pint,litre,0.568261

inch,centimetre,2.54
mile, Inch, 63360.0

Sorry my bad, this is how it is laid out in the txt file.

One way to work around this, is to check if the array is empty before assigning the data:

for (int i = 0; i < fileLn.Length - 1; i++)
{
    SplitData = fileLn[i].Split(',');
    if(SplitData.Length == 3)
    {
        To = SplitData[0];
        From = SplitData[1];
        Factor = Convert.ToDouble(SplitData[2]);
        Console.WriteLine(To + " - " + From + " - " + Factor + " - ");
        string[] Measurements = Input.Split(',', ' ', '/', '.');
        Amount = Convert.ToDouble(Measurements[0]);
        j = Measurements[1];
        l = Measurements[2];
        if (j == To)
        {
            Output = (Factor * Amount);
            Console.WriteLine("{0} {1} is equal to {2} {3}", Amount, Measurements[1], Output, Measurements[2]);
            Console.ReadLine();
            goto Main;
            //break;
        }
        else
        {
           // Console.WriteLine("Not Matched");
           // Console.ReadLine();
        }
    }
}

Prefect thank you, works great now. The only problem left is now when I try to do a conversion with the pound kilogram it doesn't seem to read the line for that conversion? It seems to read just the first word and then uses the pound ounce conversion instead? For example 10,pounds,kilograms is equal to 2.26796 kilograms but the result that is displayed is 160 kilogram which is completely wrong. I have tried using an if statement and it doesn't seem to work with that, any ideas?

You're only checking if the To variable matches:

if (j == To)

You need to check if both the To and the From variables match:

if (j == To && l == From)

On a side note, the IO.File class has a ReadAllLines method that will read all the lines in a file and return a string array containing the data:

string[] fileLn = File.ReadAllLines(@"..convert.txt")

replaces

string[] fileLn; // This is another srting called fileLn.
StreamReader Units = new StreamReader(@"..convert.txt"); // This is file path to find the convert.txt file.
while ((line = Units.ReadLine()) != null) // This is the start of the while loop.
{
    lineTotal += line + "\n"; // This is count the total amount of lines in txt file.
}
fileLn = lineTotal.Split('\n'); 

Sweet thank you for your help. The only problem is that now when I check for both of the varibles it works fine until I try and covert a mile to inch, it just shuts down for no reason and doesn't come up with an error saying why it has done this ?

In your testing, are you spelling inch right? I noticed in the text file inch starts with a capital but none of the others do. Spelling inch with a lower case i, could explain the behavior you're seeing.

In looking at your data again I noticed another anomaly, an extra space. To make your program more robust few more changes might need to be made. Homogenizing the data will allow your checking to be more reliable. The ToLower method of the string class and including the space as a delimiter for the Split method will help with this:

    static void Main(string[] args)
    {
        string To, From, j, l;// These are the strings for the program, which includes the line total to count the amount of lines in the text file.
        double Factor, Output, Amount; //These are the double varibles which will be floating point number varibles.// This is setting up the array for the program.
        string[] fileLn = File.ReadAllLines("TextFile1.txt");
        string Input = "";
        while(Input != "quit")
        {
            //This is getting the inputs from the user.
            Console.WriteLine("Please input the amount, to and from type (Ex. 5,ounces,grams)(quit to exit):"); // This is displayed on the console for the user to read.
            Input = Console.ReadLine().ToLower(); // This puts the inputs as strings.
            if(Input != "quit")
            {
                for (int i = 0; i < fileLn.Length - 1; i++)
                {
                    string[] SplitData = fileLn[i].ToLower().Split(", ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    if (SplitData.Length == 3)
                    {
                        To = SplitData[0];
                        From = SplitData[1];
                        Factor = Convert.ToDouble(SplitData[2]);
                        Console.WriteLine(To + " - " + From + " - " + Factor + " - ");
                        string[] Measurements = Input.Split(',', ' ', '/', '.');
                        Amount = Convert.ToDouble(Measurements[0]);
                        j = Measurements[1];
                        l = Measurements[2];
                        if (j == To && l == From)
                        {
                            Output = (Factor * Amount);
                            Console.WriteLine("{0} {1} is equal to {2} {3}", Amount, Measurements[1], Output, Measurements[2]);
                            Console.ReadLine();
                            //break;
                        }
                        else
                        {
                            //Console.WriteLine("Not Matched");
                            //Console.ReadLine();
                        }
                    }
                }
            }
        }
    }

On a side note, I just noticed that you're using goto and a label. While technically allowed by the C# language, is considered poor programming and can lead to big problems in larger programs. If you look at my code, you'll see I replaced that with a while loop and included an exiting instruction for the user.

I have just done another test with a captital I and lower i and the problem is still occuring ?

Sorry there is a bug in your code that I missed. In a for loop, when testing for the limit, when you use less than(<) it already stops at one less than the limit, you don't need to subtract 1:

for (int i = 0; i < fileLn.Length; i++)

Alright I have taken out the -1 but the problem is still occuring when I try to convert the 1,mile,inch as it just shuts down with no error given ?

Sorry my bad there was an error in the txt file. The problem is now sorted and thankyou for your support.

If you question is answered please remember to mark this solved. Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.