user3328039
user3328039

Reputation: 79

"Input string was not in a correct format" error

The following Script shows the

"index was outside the bounds of the array"

at line

for (int i = 0; i <u_f.GetLength(1); i++)

when I change it to

for (int i = 0; i <=u_f.GetLength(1); i++)

it shows

"Input string was not in a correct format"

error in line int uid = Convert.ToInt32(txtbx_id.Text);

        float userscore,itemscore,result;
        string lineitem, lineuser;
        //float[][] a = new float[89395][100];
        //float[][] b = new float[1143600][100];
        float[][] a = Enumerable.Range(0, 89395).Select(i => new float[100]).ToArray();
        float[][] b = Enumerable.Range(0, 1143600).Select(j => new float[100]).ToArray();
        //float[,] c = new float[89395, 100];
        StreamReader fileitem = new StreamReader("c:\\1.txt");
        StreamReader fileuser = new StreamReader("c:\\2.txt");
    public Form1()
    {
        InitializeComponent();
        for (int x = 0; x <= 8939500; x++)
        {
            lineuser = fileuser.ReadLine();
            if (!string.IsNullOrEmpty(lineuser))
            {
                string[] values = lineuser.Split(' ');
                int userid, factoriduser;
                foreach (string value in values)
                {
                    userid = Convert.ToInt32(values[0]);
                    factoriduser = Convert.ToInt32(values[1]);
                    userscore = Convert.ToSingle(values[2]);
                    a[userid][factoriduser] = userscore;
                }
            }
        }

        for (int y = 0; y <= 114360000; y++)
        {
            lineitem = fileitem.ReadLine();
            if (!string.IsNullOrEmpty(lineitem))
            {
                string[] valuesi = lineitem.Split(' ');
                int itemid, factoriditem;
                foreach (string value in valuesi)
                {
                    itemid = Convert.ToInt32(valuesi[0]);
                    factoriditem = Convert.ToInt32(valuesi[1]);
                    itemscore = Convert.ToSingle(valuesi[2]);
                    b[itemid][factoriditem] = itemscore;
                }
            }

        }

    }
    public float dotproduct(int userid,int itemid)
    {

        //get the score of 100 from user and item to dotproduct
        float[] u_f = a[userid];
        float[] i_f = b[itemid];

        for (int i = 0; i <u_f.GetLength(1); i++)  //<----error
        {
            result += u_f[userid] * i_f[itemid];
        }
        return result;

    }

    private void btn_recomm_Click(object sender, EventArgs e)
    {
        if(txtbx_id.Text==null)
        {
            MessageBox.Show("please insert user id");
        }
     if (txtbx_id.Text != null && txtbx_itemid==null)
      {
       int sc = Convert.ToInt32(txtbx_id.Text);
       if (sc>=0 &&sc<=89395)
        {
          for (int z=0;z<=1143600;z++)
            {
              dotproduct(sc,z);
            }
          Hashtable hashtable = new Hashtable();
           //put the result in hashtable
             foreach (DictionaryEntry entry in hashtable)
               {
                 System.Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
               }
        }
     }
        if (txtbx_id!=null && txtbx_itemid!=null)
        {
            int uid = Convert.ToInt32(txtbx_id.Text);     //<----error
            int iid = Convert.ToInt32(txtbx_itemid.Text); 
            {
                if (uid>=0 && uid<=89395 && iid>=0 && iid<=1143600)
                {
                    dotproduct(uid,iid);
                    MessageBox.Show("The Score of user id "+uid+" is "+result);
                }
            }
        }

Upvotes: 1

Views: 38245

Answers (4)

delliottg
delliottg

Reputation: 4140

I also ran into this error when I had a single curly brace in a string (and the exception wasn't very helpful in figuring it out):

string result = string.Format("{label: '{0}, {1}', children: [", prefixLabel, prefixPointer);

---------------------------------------------------^-----------------------------

The solution in this case is doubled curly braces: {{ EG:

string result = string.Format("{{label: '{0}, {1}', children: [", prefixLabel, prefixPointer);

---------------------------------------------------^-----------------------------

I discovered that if I removed the curly brace just before the word label, the problem went away, so I Googled how to escape it. Here's the link to the original SO Question I found on escaping curly braces, and it has many more links if you need more reading.

Hopefully this helps someone else who's confused by the “Input string was not in a correct format” error when they had no integers in their string similar to my experience just now.

Upvotes: 0

D Stanley
D Stanley

Reputation: 152556

Your two errors are unrelated. THe reason you're getting an error on

for (int i = 0; i < u_f.GetLength(1); i++)

is because u_f one has one dimension, but you are asking for the length of the second dimnsion (GetLength takes a 0-based dimension index).

Just use

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

Your other error is caused by txtbx_id.Text not representing a valid int value.

In addition, this method is guaranteed to fail, because an array of length x does not have a value at array[x] (array[x-1] is the last item in the array):

public float dotproduct(int userid,int itemid)
{
    //get the score of 100 from user and item to dotproduct
    float[] u_f = a[userid];
    float[] i_f = b[itemid];

    for (int i = 0; i <u_f.GetLength(1); i++)  
    {
        result += u_f[userid] * i_f[itemid];  // this is GUARANTEED to fail 
    }
    return result;
}

I think you want

    for (int i = 0; i <u_f.Length; i++)  
    {
        result += u_f[i] * i_f[i];  
    }

instead.

Upvotes: 1

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

"index was outside the bounds of the array"

Problem 1: You are accessing the GetLength(1) elements from invalid dimension. you have only 1 dimension array but accessing second dimension Length as always Array Index starts from zero.

Solution 1: You should use GetLength(0) or Length as your array is single dimensional array.

Array.GetLength(0) returns the number of elements in the first dimension of the Array.

From MSDN:

Gets a 32-bit integer that represents the number of elements in the specified dimension of the Array.

Replace This:

for (int i = 0; i <u_f.GetLength(1); i++)  

With This:

for (int i = 0; i <u_f.GetLength(0); i++)  

OR With

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

Problem 2: you are doing null check for TextBox control directly but not for TextBox Text/Value. so what happens here is even if user does not enter any value in your textbox the if condition willnot fail as TextBox is not null.so it enters the if block but when it tries to convert that empty string/value into integer using following statement :

int uid = Convert.ToInt32(txtbx_id.Text);     //<----error

as you said it throws exception.

Solution 2: You need to perform null check for TextBox value like TextBox1.Text!=null

Suggestion 1: You can use String.IsNullOrWhiteSpace() method to verify wether value is Null,Empty or WhiteSpace.

Suggestion 2: if you want to avoid runtime exceptions while parsing the user input into integer, you need to use int.TryParse() method.

Replace This:

if (txtbx_id!=null && txtbx_itemid!=null)
    {
        int uid = Convert.ToInt32(txtbx_id.Text);     //<----error
        int iid = Convert.ToInt32(txtbx_itemid.Text); 
        {
            if (uid>=0 && uid<=89395 && iid>=0 && iid<=1143600)
            {
                dotproduct(uid,iid);
                MessageBox.Show("The Score of user id "+uid+" is "+result);
            }
        }
    }

With This:

if (!String.IsNullOrWhiteSpace(txtbx_id.Text) &&      
     !String.IsNullOrWhiteSpace(txtbx_itemid.Text)) 
{
  int uid,iid;     
  if(int.TryParse(txtbx_id.Text,out uid) && int.TryParse(txtbx_itemid.Text,out iid))      
  {
    if (uid>=0 && uid<=89395 && iid>=0 && iid<=1143600)
    {
      dotproduct(uid,iid);
      MessageBox.Show("The Score of user id "+uid+" is "+result);
    }
   }
}

Upvotes: 4

Patrick Hofman
Patrick Hofman

Reputation: 156978

Referring to the problem:

int uid = Convert.ToInt32(txtbx_id.Text);     //<----error

Try to use Int32.TryParse when having use input that can be different then expected:

int uid;
if (!Int32.TryParse(txtbx_id.Text, out uid))
{
    MessageBox.Show("Input is not a number! Try again!");
}

Upvotes: 1

Related Questions