Home > OS >  my program is not returning the answer in C#. help please
my program is not returning the answer in C#. help please

Time:07-07

This is the class that I created to check the activity of mosquitoes and When I call it in the main function I am not getting the output.

public class Mosqactivity
{
    public string Mating (int age)
    {
        string a ="";
        if (age==12)
        {
            a="mosquito is in mating";
        }
        return a;
    }
    public string Blood (int age)
    {
        string b ="";
        if (age==13||age==14)
        {
            b="Searching blood";
        }
        return b;
    }
    public string Resting (int age)
    {
        string c ="";
        if (age==15||age==16||age==17)
        {
            c="Resting";
        }
        return c;
    }
    public string Layeggs (int age)
    {
        string d="";
        if (age==18||age==23||age==28)
        {
            d="Lay Eggs";

        }
        return d;
        
    }
}

code in the main function

public static int Main(string[] args)
{
    int day=0;
    Mosqactivity act;
    act = new Mosqactivity ();
    string result="";
    Console.WriteLine("Enter a number \n");
    Console.ReadLine(); result=act.Mating(day);
    result=act.Layeggs(day);
    result=act.Blood(day);
    result=act.Resting(day);
    Console.WriteLine(result);

    return 0;
}

I expected the code to give output like 'Mosquito is mating" or Search for blood or Resting or Lay eggs as it is checking in the function, but after entering the number it finish the process.

CodePudding user response:

many issues in code but here the relevant ones:

Console.ReadLine(); 

is maybe reading some input but you are missing the assignment to a variable in code... so in the end, you are calling all the methods with the parameter int day=0;

No method at all is having a check for the case day == 0 (actually 'age', coz you named the parameter like that) so all those are returning an empty string

additionally to this, you are printing only the last assignment of the "result" variable.

result=act.Layeggs(day);
result=act.Blood(day);
result=act.Resting(day);
Console.WriteLine(result);

instead you should do somethin like:

Console.WriteLine("Layeggs? "   act.Layeggs(day));

or

result = act.Layeggs(day);
Console.WriteLine("Layeggs? "   result);

CodePudding user response:

support this is testing code,right? you can add Console.WriteLine after each act.Method(), you can see the output.

the first three invoking are overwrited by the last

result=act.Mating(day);
result=act.Layeggs(day);
result=act.Blood(day);
result=act.Resting(day);
  •  Tags:  
  • c#
  • Related