2 Replies - 1049 Views - Last Post: 16 November 2012 - 07:24 AM Rate Topic: -----

#1 Stephen68  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 24
  • Joined: 08-April 11

type of value checking

Posted 15 November 2012 - 11:04 PM

Hello!

I have a loop that will read lines from a file until it hits the 16th. It then grabs that line
splits it up and I store 3 of the values form the line into 3 different arrays. The problem
I'm having is that sometimes it not a double for some reason. Meaning the text file was not
made in the right format.

How would I go about not reading them? do I make an "if" for each array?

Code below


 while ((line = file.ReadLine()) != null)
                {
                    if (lineCount == 15)
                    {
                        
                         holder = line.Split(',');
                         elong.Add((double)Convert.ToDouble(holder[2]));
                         breakStr.Add((double)Convert.ToDouble(holder[3]));
                         mod.Add((double)Convert.ToDouble(holder[4]));
                         break;
                    }
                    lineCount++;
                }   
                



Thanks for any help I may get, have a great day

Stephen

Is This A Good Question/Topic? 0
  • +

Replies To: type of value checking

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4187
  • View blog
  • Posts: 11,847
  • Joined: 18-April 07

Re: type of value checking

Posted 15 November 2012 - 11:26 PM

Look up the method of the Double object called TryParse. This method will try to parse a value into a double and if successful, it will return true and places the double into the parameter which marked as "out". If it fails, it will return false.

if (Double.TryParse(holder[2],someDoubleVar)) { elong.add(someDoubleVar); }



Here we try and parse holder[2] into a double and if successful, the double is placed in "someDoubleVar" and return true. This will cause it to go into the body of the if statement and add the value to the elong array.

If it is false, it will never make it into the array. You can use this to create an else statement afterwards that puts in a default value for elong.add or simply not add to the array. Whatever fits your design best.

In short you have to test the value from a file just as if it was input from the user and that in either case you should always check to see if a value will convert successfully and take precautions in case it doesn't.

Hope that answers the question. :)

This post has been edited by Martyr2: 15 November 2012 - 11:27 PM

Was This Post Helpful? 1
  • +
  • -

#3 Stephen68  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 24
  • Joined: 08-April 11

Re: type of value checking

Posted 16 November 2012 - 07:24 AM

Works like a charm, thanks for your time

Stephen
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1