I'm trying to create a program that converts a 5 digit binary number to decimal. As it stands, the conversion works perfectly, but I'm having trouble with giving an error message if the user inputs a number larger than 1.
for (int i = 4; i>=0; i--)
{
digit = txt_input.Text.Substring(i,1);
num = Convert.ToInt32(digit);
//If a digit is 1 or 0
if (num <= 1)
{
total += num * (Math.Pow(2, x));
x += 1;
goahead = 1;
}
//If a digit is not 1 or 0
if (num > 1)
{
lst_output.Items.Add("All digits must be either 1 or 0.");
i = 10;
goahead = 0;
}
}
When the user inputs 1's or 0's the program works as intended, but when a number larger than 1 is inputted, I get the error "startIndex cannot be larger than length of string" on line 3.
If a number with more or less than 5 digits is inputted, the user gets a message saying that the number must be 5 digits long. So as far as I can tell, the problem isn't the size of the startIndex. Especially since, no matter what the user inputs, startIndex remains unchanged.
Imagine your input is 10103
.
Now pay attention to this part of the code:
if (num > 1)
{
lst_output.Items.Add("All digits must be either 1 or 0.");
i = 10;
goahead = 0;
}
Why are you making i = 10
here?
So if you input is the above string, in the first iteration you'd go into the if
statement above, add the message to lst_output
, then set i
to 10
. Then you go back to the for
loop and the i >= 0
condition is still true so you go inside the for
loop once again. Now your i = 1
, but your string is of length 5.
So;
digit = txt_input.Text.Substring(i,1);
Here now you're trying to take a substring of length 1 that starts at the index = 10
, from a string that is only 5 characters long.
Of course it would throw
startIndex cannot be larger than length of string. Parameter name: startIndex.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments