Hello, I’m working on this task:
Method Comparator.Compare compares 2 boxes by their volume and returns 1 if the first one is bigger than the second one, -1 if the second one is bigger than the first one, or 0 if the boxes are equal.
Modify the code in a way that class Box uses the Comparator.Compare method to be compared to another box. Depending on the result of the comparison, CompareTo should return “Bigger” if the current box is bigger than box, “Smaller” if the current box is smaller than box, and “Equal” if the boxes are equal.
In the Main, method, read Width, Height, and Length from the console for two boxes and output the result of box1.CompareTo(box2).
For example:
>100
>200
>300
>4
>5
>6
Bigger
Here is my code:
namespace This
{
class Box
{
public int Width;
public int Height;
public int Length;
public string CompareTo(Box box)
{
if (Comparator.Compare(box1, box2) == 1) // Compare 2 boxes here and return the result
this.box = "Bigger";
else if (Comparator.Compare(box1, box2) == -1)
this.box = "Smaller";
else if (Comparator.Compare(box1, box2) == 0)
this.box = "Equal";
}
}
class Comparator
{
public static int Compare(Box box1, Box box2)
{
var volume1 = box1.Width * box1.Height * box1.Length;
var volume2 = box2.Width * box2.Height * box2.Length;
if (volume1 > volume2)
return 1;
if (volume1 < volume2)
return -1;
return 0;
}
}
class BoxComparator
{
public static void Main()
{
var box1 = new Box();
int width1 = int.Parse(Console.ReadLine());// Create 2 boxes here and output the comparation result
int height1 = int.Parse(Console.ReadLine());
int length1 = int.Parse(Console.ReadLine());
var box2 = new Box();
int width2 = int.Parse(Console.ReadLine());
int height2 = int.Parse(Console.ReadLine());
int length2 = int.Parse(Console.ReadLine());
Console.WriteLine(box1.CompareTo(box2));
}
}
}
Привіт! Допоможіть, будь ласка, я не зрозуміла логіку завдання, і наробила щось weird у коді.
Заплуталася, чому у методі CompareTo стоїть комментар // Compare 2 boxes here and return the result, якщо ми вже порівняли у методі Compare…
Can anyone please help me to solve it?