Maha

Maha

  • NA
  • 0
  • 311.6k

Step in CompareTo() method

Oct 1 2012 3:46 AM
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;
}
}

Answers (4)