Why it is incorrect to include a step like this in CompareTo() method. Step is highlighted in the program.
using System;
namespace _111111111
{
class Program
{
static void Main(string[] args)
{
School[] school = new School[3];
string[] names = { "AAAA", "BBBB", "CCCC" };
for (int x = 0; x < school.Length; ++x)
{
school[x] = new School(names[x]);
Console.Write("Enrollment No ");
school[x].setStudentEnrolled(int.Parse(Console.ReadLine()));
}
Console.WriteLine("\nBefore Sort");
for (int x = 0; x < school.Length; ++x)
Console.WriteLine("School Name {0} No of student {1}", school[x].getName(), school[x].getStudentEnrolled());
Array.Sort(school);
Console.WriteLine("\nAfter Sort");
for (int x = 0; x < school.Length; ++x)
Console.WriteLine("School Name {0} No of student {1}", school[x].getName(), school[x].getStudentEnrolled());
Console.Write("\nMinumum enrollment is ");
int minimum = int.Parse(Console.ReadLine());
bool trueORfalse = false;
for (int x = 0; x < school.Length; ++x)
{
if (minimum < school[x].getStudentEnrolled())
{
Console.WriteLine("School Name {0} No of student {1}", school[x].getName(), school[x].getStudentEnrolled());
trueORfalse = true;
}
}
if (!trueORfalse)
{
Console.WriteLine("All the enrollment figures are less than {0}", minimum);
}
Console.ReadKey();
}
}
}
class School : IComparable
{
string schooName;
int studentEnrolled;
public School(string schooName)
{
this.schooName = schooName;
}
public string getName()
{
return schooName;
}
public void setStudentEnrolled(int studentEnrolled)
{
this.studentEnrolled = studentEnrolled;
}
public int getStudentEnrolled()
{
return studentEnrolled;
}
public int CompareTo(object o)
{
int returnVal;
School temp = (School)o;
if (this.studentEnrolled > temp.studentEnrolled)
returnVal = 1;
else
if (this.studentEnrolled < temp.studentEnrolled)
returnVal = -1;
else
if (this.studentEnrolled == temp.studentEnrolled)
returnVal = 0;
return returnVal;
}
}
Loading
Posted Oct 1, 2012, 7:55 AM
VulpesPosted Oct 1, 2012, 7:49 AM
The reason why it won't compile unless you comment that line out is because the C# compiler thinks that there is a case which is not covered because the 'if' statement doesn't end with a simple 'else'.
To make it compile with that line left in you'd have to initialize the returnValue variable before the 'if' statement starts:
int returnVal = 0;
though, if you do that, the final 'else if' (or even just 'else') is superfluous in any case.
Posted Oct 1, 2012, 7:20 AM
//if (this.studentEnrolled == temp.studentEnrolled)
VulpesPosted Oct 1, 2012, 5:33 AM
If you have two integers, a and b, then one of the following must be true:
1. a > b
2. a < b
3. a == b
So, if the first two cases are false, then the last one must be true.