import java.util.Scanner;
public class SortPurchasesArray {
public static void main(String[] args) {
// Write your code here
//create a Scanner class object
Scanner scan=new Scanner(System.in);
//create of 5 Purchase objects
Purchase[] p=new Purchase[5];
//declare a string variables
String choice;
//read sales amount and invoice for five Purchase objects
for (int i = 0; i < p.length; i++)
{
p[i]=new Purchase();
System.out.printf("Enter sale amount,$: ");
double sales=Double.parseDouble(scan.nextLine());
System.out.printf("Enter invoice number#: ");
int invoice=Integer.parseInt(scan.nextLine());
p[i].setInvoiceNumber(invoice);
p[i].setSaleAmount(sales);
}
//do while continues until user enters 'Z' to stop loop
do
{
System.out.println("***Menu***");
System.out.println("a. sort by sales");
System.out.println("b. sort by invoice");
System.out.println("Enter your choice or Z to exit: ");
choice=scan.nextLine();
//check if choice is "a"
if(choice.equals("a"))
{
sortBySaleAmount(p);
display(p, "Sort By Sales");
}
//check if choice is "b"
else if(choice.equals("b"))
{
sortByInvoice(p);
display(p, "Sort By Invoice");
}
}while(!choice.equals("Z"));
}
/*static method , sortBySaleAmount that takes Purchase array
* and then sort the data by sales amount. */
}
public static void sortBySaleAmount(Purchase[] array) {
// Write your code here
int n = array.length;
Purchase temp = null;
for(int i=0; i < n; i++)
{
for(int j=1; j < (n-i); j++)
{
if(array[j-1].getSaleAmount()> array[j].getSaleAmount())
{
//swap elements
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}
}
/*static method , sortByInvoice that takes Purchase array
* and then sort the data by invoice account number. */
}
public static void sortByInvoice(Purchase[] array) {
// Write your code here
int n = array.length;
Purchase temp = null;
for(int i=0; i < n; i++)
{
for(int j=1; j < (n-i); j++)
{
if(array[j-1].getInvoiceNumber()> array[j].getInvoiceNumber())
{
//swap elements
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}
}
/*static display method that takes a Purchase array and message
* as input arguments and then display the Purchase and message*/
}
public static void display(Purchase[] p, String msg) {
// Write your code here
// Write code here
System.out.println(msg);
for (int index = 0; index < p.length; index++)
{
p[index].display();
}
}//end of the display method
}
}
}