Reputation: 1081
So I have this code
static void Main(string[] args)
{
Console.Write("First Number = ");
int first = int.Parse(Console.ReadLine());
Console.Write("Second Number = ");
int second = int.Parse(Console.ReadLine());
Console.WriteLine("Greatest of two: " + GetMax(first, second));
}
public static int GetMax(int first, int second)
{
if (first > second)
{
return first;
}
else if (first < second)
{
return second;
}
else
{
// ??????
}
}
is there a way to make GetMax return a string with error message or something when first == second.
Upvotes: 25
Views: 61459
Reputation: 1065
Since you want to display the output like this
Console.WriteLine("Greatest of two: " + GetMaxString(first, second));
I'd have the GetMax function return a string:
public static string GetMaxString(int first, int second)
{
return (first > second) ? first.ToString() : (second > first) ? second.ToString() : "The two values are equal";
}
Upvotes: 0
Reputation: 3
static void Main(string[] args)
{
Console.Write("First Number: ");
int number1 = int.Parse(Console.ReadLine());
Console.Write("Second Number: ");
int number2 = int.Parse(Console.ReadLine());
var max = (number1 > number2) ? number1 : number2;
Console.WriteLine("Greatest Number: " + max);
}
Upvotes: 0
Reputation: 718
If possible to use the List type, we can make use of the built in methods Max() and Min() to identify the largest and smallest numbers within a large set of values.
List<int> numbers = new List<int>();
numbers.Add(10);
numbers.Add(30);
numbers.Add(30);
..
int maxItem = numbers.Max();
int minItem = numbers.Min();
Upvotes: 1
Reputation: 30698
Since you are returning greater number, as both are same, you can return any number
public static int GetMax(int first, int second)
{
if (first > second)
{
return first;
}
else if (first < second)
{
return second;
}
else
{
return second;
}
}
You can further simplify it to
public static int GetMax(int first, int second)
{
return first >second ? first : second; // It will take care of all the 3 scenarios
}
Upvotes: 4
Reputation: 7764
static void Main(string[] args)
{
Console.Write("First Number = ");
int first = int.Parse(Console.ReadLine());
Console.Write("Second Number = ");
int second = int.Parse(Console.ReadLine());
Console.WriteLine("Greatest of two: " + GetMax(first, second));
}
public static int GetMax(int first, int second)
{
if (first > second)
{
return first;
}
else if (first < second)
{
return second;
}
else
{
throw new Exception("Oh no! Don't do that! Don't do that!!!");
}
}
but really I would simply do:
public static int GetMax(int first, int second)
{
return first > second ? first : second;
}
Upvotes: 16