質問

I am trying to get the output from a method i wrote in a different class to return a value into the middle of a writeline statement. The error "Operator '+' cannot be applied to operands of type 'string' and 'method group" is stopping anything from running, but I cant seem to find away to get the error resolved. This may be a real simple thing I am missing, but im still really new to programming so Im probably missing something obvious.

    public void EatFruits()
    {
        double dblpercent;
        this.MakeFruits();
        Console.WriteLine("You have an Apple and a Banana in your fruit garden.");
        Console.WriteLine("What Percent of the Apple would you like to eat?");
        dblpercent = Convert.ToDouble(Console.ReadLine());
        Console.WriteLine("What Percent of the Banana would you like to eat?");
        dblpercent = Convert.ToDouble(Console.ReadLine());
        Console.WriteLine("You have " + (apple.Eat) + "% of your apple and " + (banana.Eat) + "% of your banana left.");
    }

And the code for the Eat method in the other class is:

    public double Eat(double dblpercent)
    {
        return (PercentFruitLeft-dblpercent);
    }

PercentFruitLeft was set up early with a value of 100, and then decreased by whatever the user types in for how much they want to eat.

役に立ちましたか?

解決

Method group is an expression used in the C# standard to describe a group of one or more overloaded methods identified by their common name. In this case, the compiler is referring to apple.Eat and banana.Eat method groups.

You need to call your method with a parameter in parentheses following the name of the method. In addition, you need separate dblpercent variables for the apples and for the bananas:

Console.WriteLine("What Percent of the Apple would you like to eat?");
double dblpercentApple = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("What Percent of the Banana would you like to eat?");
double dblpercentBanana = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("You have " + (apple.Eat(dblpercentApple)) + "% of your apple and " + (banana.Eat(dblpercentBanana)) + "% of your banana left.");

Rather than composing your strings manually with concatenations, you could use formatting, like this:

Console.WriteLine("You have {0}"% of your apple and {1}% of your banana left.", apple.Eat(dblpercentApple), banana.Eat(dblpercentBanana));

This gives your code additional clarity by keeping the template of the string that you write together in a single string.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top