2

I have the attached code which trys to find all 1s in an array input by the user. The program asks the user to select the array size, then input a number of that size with some 1s in it. It then counts the number of 1s found.

I guess that the input the user gives is in the form of a string? So, if they input 12345 it would be a string with one 1 in it.

I am trying to convert the array to int32, though I don't think I fully understand why it has to be int32 either.

If somebody could help me understand this programs' workings and why I'm getting the following error I'd be thankful.

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: Input string was not in a correct format.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace count1s
{
    class Program
    {
        static void Main(string[] args)
        {
            int count = 0;
            Console.WriteLine("Enter a number for the array length");
            int limit = int.Parse(Console.ReadLine());

            int[] array1s = new int[limit];
            Console.WriteLine("Enter a number with some 1s in it");

            for(int i=0; i<limit; i++)
            {
                array1s[i] = Convert.ToInt32(Console.ReadLine());
            }
            foreach (int number in array1s)
            {
                if (number == 1)
                {
                    count++;
                }
            }
            Console.WriteLine("The number of 1s in the array is: {0}", count);
            Console.ReadLine();
        }
    }
}
3
  • What input are you giving it? Commented Jul 16, 2015 at 8:43
  • I'm confused. Do you want to count have many "1" there is in each number entered, or do you want to count how many times the user enters "1" as an element in the array? Commented Jul 16, 2015 at 8:47
  • Are you deliberately reading limit lines from the user, rather than reading one line and then counting how many digits are '1'? Commented Jul 16, 2015 at 8:51

5 Answers 5

2

You are getting this error because you are entering the array elements in one line.

If you enter one element on one line then program will work fine.

If you want to accept numbers on one line then you can use split function like

String []numbers = Console.ReadLine().Split(' ');
for (int i = 0; i < limit; i++)
{
    array1s[i] = Convert.ToInt32(numbers[i]);
}
foreach (int number in array1s)
{
    if (number == 1)
    {
        count++;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

G-Man. Can I ask also, why is it so important to understand about Unicode and Character Sets. As in, what type of trouble will I get into, if I don't fully comprehend these things?
1

I don't think I fully understand why it has to be int32 either.

It doesn't have to be. That depends on your input. If the user enters a number small enough, it can also fit into a short (which is 16 bits), and you can parse the string into that.

why I'm getting the following error

Because you're trying to parse a string which isn't parse-able to a valid int value. If you're not sure the input is valid, you can use a method such as int.TryParse, which returns a boolean indicating the success or failure of the parsing:

int i = 0;
while (i < limit)
{
    string value = Console.ReadLine();
    int parsedValue;

    if (!int.TryParse(value, out parsedValue))
    {
        Console.WriteLine("You've entered an invalid number. Please try again");
        continue;
    }

    array[i] = parsedValue;
    i++;
}

If you want to count all occurrences of 1, you can simply use Enumerable.Count which takes a predicate:

return array.Count(number => number == 1);

4 Comments

From my research on this, .NET strings use UTF-16, which takes two bytes per character (code points). So, we use Int32 just to be safe as we don't know what the user will input, as in a foreign character with an accent maybe?
Also please, I traced the program flow through the debugger and was surprised to see that each time I input a character into the console and hit return it returned to the for loop, in original code posted, and added the character to the array. So, this is a bit of a black box for me, as in, how is this information travelling from the IDE to the console. Is it going into memory on the stack / heap? Sorry, this may sound an ambiguous or stupid question. I'm just a bit confused about the flow of information, I guess.
@user2036750 The user can input any number he wants. That number may exceed 32bit. This has nothing to do with string representation. You can also choose to parse it into a long, which is 64bit in .NET, "just to be on the safe side". But, that is usually an overkill.
@user2036750 Regarding program flow - The Console class represents any interaction with the windows console based application. It is connected via input and output streams to the operating system. Everytime you type a line and press enter, the Console class detects that and flows the information through to your application, via Console.ReadLine().
1

Use this as

for(int i=0; i<limit; i++)
{
    int value;
    var isNumber = int.TryParse(Console.ReadLine(), out value);
    if(isNumber)
    {
       array1s[i] = value;
    }
    else
    {
       Console.WriteLine("Invalid value you have entered");
       continue;
    }
}

Comments

0

Well, now I feel like a bit of an idiot. I tried some of your responses, thanks very much for that, and they are good. I went back and tried the code I originally posted as well and found that it does work. I just need to hit carriage return after each entry into the array. I'll take a look at all of this properly later to find out what is going on.

Thanks again all - gotta say - was really surprised to get so many responses on here so quickly. Awesome!!

Comments

0

I just found a really good article on the Microsoft: DEV204x Programming with C# course I have started online. I think this will be helpful to all who follow with the same questions I had. Hopefully I'm not breaking any copyright laws or stackoverflow rules. It's a free course, so I doubt it.

Data Conversions

C# supports two inherent types of conversion (casting) for data types, implicit and explicit. C# will use implicit conversion where it can, mostly in the case when a conversion will not result in a loss of data or when the conversion is possible with a compatible data type. The following is an example of an implicit data conversion.

Converting from smaller to larger integral types:

int myInt = 2147483647;
long myLong= myInt;

The long type has a 64-bit size in memory while the int type uses 32-bits. Therefore, the long can easily accomodate any value stored in the int type. Going from a long to an int may result in data loss however and you should use explicit casting for that.

Explicit casts are accomplished in one of two ways as demonstrated with the following coe sample.

double myDouble = 1234.6;
int myInt;
// Cast double to int by placing the type modifier ahead of the type to be converted
// in parentheses
myInt = (int)myDouble;

The second option is to use the methods provided in the .NET Framework.

double myDouble = 1234.6;
int myInt;
// Cast double to int by using the Convert class and the ToInt32() method.
// This converts the double value to a 32-bit signed integer
myInt = Convert.ToInt32(myDouble);

You will find many other methods in the Convert class that cast to different integral data types such as ToBoolean(), ToByte(), ToChar(), etc.

The Convert.ToInt32() method can also be used to cast a string literal to a numeric data type. For example, you may have GUI-based application in which uses input data into text boxes. These values are string values when passed to the code in your application. Use of the above method to cast the string to numbers can help prevent exceptions in your code when trying to use the wrong data type in a specific area.

C# also provides another mechanism to deal with casting types. The use of the TryParse() method and Parse() methods can help with casting as well. These methods are attached to the types in C# rather than the Convert class. An example will help demonstrate.

// TryParse() example
bool result = Int32.TryParse(value, out number);
// Parse() example
int number = Int32.Parse(value);

In the TryParse() example, the method returns a Boolean result indicating if the conversion succeeded. In the Parse() example, if the conversion does not succeed, an exception will be thrown.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.