Answer to Question #272459 in C# for cphil

Question #272459

This is my current try catch statement. I dont know why it exists when empty file read in:

 // convert each string into an integer and store in "eachInt[]"

      string fileContents = System.IO.File.ReadAllText(fileName);

      string[] eachString = fileContents.Split(new char[] { '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

      int[] eachInt = new int[eachString.Length];

      try

      {

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

        {

          if (IsNumeric(eachString[i]))

          {

            eachInt[i] = int.Parse(eachString[i]);

          }

          // else

          //{

           // continue;

          //}

        }

        eachInt = eachInt.Where(val => val != 0).ToArray();

      }

      catch(IndexOutOfRangeException)

      {

        MessageBox.Show("File contained no integers, try a different file.");

        return;

      }


1
Expert's answer
2021-11-28T05:26:01-0500
 public static int[] Read(string fileName)
        {
            string[] rows = System.IO.File.ReadAllText(fileName)
                .Split(new char[] { '\t', '\r', '\n', ' '}, StringSplitOptions.RemoveEmptyEntries);


            List<int> integers = new List<int>();


            try
            {
                for (int i = 0; i < rows.Length; i++)
                {
                    if (int.TryParse(rows[i], out int value))
                        integers.Add(value);
                }


                return integers.ToArray();
            }
            catch (Exception)
            {
                throw;
            }
        }

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS