Will Tran
Will Tran

Reputation: 41

Format Exception when trying to convert

So I'm trying to read from a text file and store each field into an array. But when I tried to convert accountNumber to an Int, I get an error.

     public bool matchCustomer(int accountID){
        string[] data = null;
        string line = Global.currentFile.reader.ReadLine();
        while (line != null)
        {
            data = line.Split('*');
            this.accountNumber = Convert.ToInt32(data[0]);
            line = Global.currentFile.reader.ReadLine();
            if (accountID == this.accountNumber)
            {
                return true;
            }

          }

        return false;
       }

Upvotes: 1

Views: 56

Answers (3)

Hari Prasad
Hari Prasad

Reputation: 16956

Other two answers addressed the issue and fix, I thought of providing another alternative which uses Linq.

You can replace complete while block content with this.

return line.Split('*').Select(s=> s.Trim().Replace(",", ""))
            .Where(c=> Regex.IsMatch(c.Trim(), @"\d+"))
            .Select(s=>int.Parse(s.Trim()))            
            .Any(e=>e == accountId);

Working Demo

Upvotes: 0

Ian
Ian

Reputation: 30813

Likely, because you split by delimiter * in the string:

12345 * Shrek * 1209 * 100,000 * 50,000

You left with a spaced number "12345 " instead of all numbers "12345". This causes it to be unconvertible. Try to apply Trim:

 this.accountNumber = Convert.ToInt32(data[0].Trim());

Also, beware of strings with thousands separator comma (50,000 and 100,000). You might need to replace it with empty string if it is unconvertible:

data[4].Replace(",","").Trim();

Upvotes: 1

Ranger
Ranger

Reputation: 1174

That's because data[0] isn't convertible into an int. What is data[0] at runtime?

You could use:

int value;
if(Int32.TryParse(data[0], out value))
{
  accountNumber = value;
}
else
{
  //Something when data[0] can't be turned into an int.
  //You'll have to decide this logic.
}

Upvotes: 1

Related Questions