Please help me with the task: "Count total number of zeroes"

Hello, I’m working on this task: Slightly modify the method AnalyzeString from the previous task. It should take two parameters, string input and ref int numberOfZeros. The method should add the number of zeros that it finds in input to numberOfZeros. From the Main method, read an integer count from the console. Then, read count strings from the console. Call AnalyzeString for every one of them. If all strings are empty, the output should be ‘All strings are invalid.’ - otherwise, output the total number of zeros in all strings.
Example 1:

4
I am y0ur father
H0ust0n, we have a pr0blem
Winter is c0mming
B0nd. James B0nd
7
Example 2:
2

All strings are invalid.

Here is my code:

using System;

namespace ParametersToMethods

{

class HowManyZer0s

{

    static void Main()

    {

        int count = int.Parse(Console.ReadLine());

        for (int i = 0; i <= count; i++)

        {

        var input = Console.ReadLine();

        int numberOfZeros;

        if (AnalyzeString(input, ref numberOfZeros))

            Console.WriteLine(numberOfZeros);

        else

            Console.WriteLine("The string is invalid.");

        }

    }

    static bool AnalyzeString(string input, ref int numberOfZeros)

    {

        numberOfZeros = 0;

        if (string.IsNullOrEmpty(input))

            return false;

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

        {

            if (input[i] == '0')

                numberOfZeros++;

        }

        return true;

    }

}

}

Hi Spydergirl1234,
Your code is close to the correct one. The issue here, I think, is in the way you output the number of zeros and “The string is invalid”. You are performing an output once per line, so if you have 4 lines of input - your program will make 4 lines of output. What is expected in this task, is to write only once to the screen the number of zeros or the error message.
This would mean to move the creation of the variable int numberOfZeros; and the output itself - outside of the for loop.

1 Like