Home > Net >  Change result to string or Int C# Console
Change result to string or Int C# Console

Time:01-10

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!.

CodePudding user response:

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}");
}
  

CodePudding user response:

One way would be to replace this

var result = 0;
if (countInput2 != iCount)
{
    result = 0;
}
else
{
    result = val/vMaxQty;
}
Console.WriteLine(result);

with

if (countInput2 != iCount)
{
    Console.WriteLine("Error!");
}
else
{
    Console.WriteLine(val/vMaxQty);
}

But Dmitry's Answer is actually more sophisticated in that it avoids the summation in the case it is not needed.

Also note: you are doing integer arithmetic! So, 2/4 = 0 => https://dotnetfiddle.net/iIpHTc That may be expected, though. Just found it worth noting.

  •  Tags:  
  • c#
  • Related