Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change result to string or Int C# Console

I have a code like:

using System;
using System.Linq;
using System.Text.RegularExpressions;
                    
public class Program
{
    public static void Main()
    {
        string input = Console.ReadLine();
        var iCount = int.Parse(input);
        int vMaxQty = 4;
        
        //Sample input2 --> 1 5 4 1 1
        string input2 = Console.ReadLine();
        int val = input2.Split(' ').Sum(x=> int.Parse(x));
        int countInput2 = Regex.Matches(input2, "\\w").Count;
        
        var result = 0;
        if (countInput2 != iCount)
        {
            result = 0;
        }
        else
        {
            result = val/vMaxQty;
        }
        Console.WriteLine(result);
    }
}

My question is: How can I change the result if 1st condition (countInput2 != iCount) is true to string. Let say, result = Error!.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Split the string, Parse, materialize into collection, but not sum and check condition(s) instead on the collection. If check succeeds, Sum:

string input2 = Console.ReadLine();

int[] data = input2
  .Split(' ')
  .Select(item => int.Parse(item))
  .ToArray(); 

int val = -1;

// You have data array instead of string; it's easy to validate it
if (iCount == data.Length) {
  val = data.Sum();

  Console.WriteLine(val);
}
else {
  Console.WriteLine($"Invalid count: expected {iCount}, actual: {data.Length}");
}
  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading