method to check the value does not work

时间:2015-06-25 18:40:35

标签: c#

I want to do is, to check which value is bigger. At first, I ask (in the console) for the first value and for the second value. Than I want to check with the method "Bigger" which value is bigger. The problem is, that the method "Bigger" is underlined and I get an error. Error: bigger_than ____ Input.Bigger ( bigger_than ____ Input . ) . " : Not all code paths return a value Error comes from following method: public int Bigger(Input none) { if (First > none.Second) { return 1; } if (Second > none.First) { return -1; } } Full Source Code: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace größer_als____ { class Program { static void Main(string[] args) { int one; int two; Console.WriteLine("bigger than..."); Console.WriteLine("one: "); Console.Write(">> "); one = int.Parse(Console.ReadLine()); Console.WriteLine("two: "); Console.Write(">> "); two = int.Parse(Console.ReadLine()); Input giveOne = new Input(); giveOne.First = one; Input giveTwo = new Input(); giveTwo.Second = two; if (giveOne.Bigger(giveTwo) == 1) { Console.WriteLine("The first one [{0}] is bigger.", giveOne); } if(giveTwo.Bigger(giveOne) == -1) { Console.WriteLine("The second one [{0}] is bigger.", giveTwo); } Console.ReadLine(); } } class Input { private int first; public int First { get { return first;} set { first = value;} } private int second; public int Second { get { return second; } set { second = value; } } public int Bigger(Input none) { if (First > none.Second) { return 1; } if (Second > none.First) { return -1; } } } }

2 个答案:

答案 0 :(得分:4)

What if neither if ever hits? you need to provide a return for every possibility. public int Bigger(Input none) { if (First > none.Second) { return 1; } if (Second > none.First) { return -1; } return 0; // <-- return something here }

答案 1 :(得分:1)

Not all code paths return a value What happens when you call Bigger() with two values that are equal? It doesn't return anything. Hence the error. Add a default condition at the end: public int Bigger(Input none) { if (First > none.Second) return 1; else if (Second > none.First) return -1; else return 0; }