7
Reply

alignment

Maha

Maha

Sep 9 2012 9:33 AM
1.2k
Whether it is possible to make output align.

Inventory list before sorting:

 Cost   On hand
 ----  -------
Pliers  5.95          3
Wrenches 8.29          2
Hammers  3.50          4
Drills  19.88          8

Inventory list after sorting:

 Cost  On hand
 ----  -------
Drills  19.88    8
Hammers            3.50  4
Pliers          5.95              3
Wrenches          8.29              2

using System;

//Add refrence to Collections namespace
using System.Collections;

class Inventory : IComparable
{
string name;
double cost;
int onhand;

public Inventory(string n, double c, int h)
{
name = n;
cost = c;
onhand = h;
}

//Overriding the ToString() method to show the output formatted
public override string ToString()
{
return
String.Format("{0, 4} {1, 9} {2, 5}", name, cost.ToString("f"), onhand);
}

// Implement the IComparable interface.
public int CompareTo(object obj)
{
Inventory b;
b = (Inventory)obj;
return name.CompareTo(b.name);
}
}

public class IComparableDemo
{
public static void Main()
{
ArrayList inv = new ArrayList();

// Add elements to the list
inv.Add(new Inventory("Pliers", 5.95, 3));
inv.Add(new Inventory("Wrenches", 8.29, 2));
inv.Add(new Inventory("Hammers", 3.50, 4));
inv.Add(new Inventory("Drills", 19.88, 8));
Console.WriteLine("Inventory list before sorting:");

Console.WriteLine("\n{0, 17} {1, 10}", "Cost", "On hand");
Console.WriteLine("{0, 17} {1, 10}", "----", "-------");

foreach (Inventory i in inv)
{
Console.WriteLine(" " + i);
}
Console.WriteLine();

// Sort the list.
inv.Sort();
Console.WriteLine("Inventory list after sorting:");
Console.WriteLine("\n{0, 17} {1, 10}", "Cost", "On hand");
Console.WriteLine("{0, 17} {1, 10}", "----", "-------");

foreach (Inventory i in inv)
{
Console.WriteLine(" " + i);
}
Console.ReadKey();
}
}


Answers (7)