a. Create a class named Salesperson. Data fields for Salesperson include an inte
ID: 3727908 • Letter: A
Question
a. Create a class named Salesperson. Data fields for Salesperson include an integer ID number and a double annual sales amount. Methods include a constructor that requires values for both data fields, as well as get and set methods for each of the data fields. Save the file as Salesperson.java.
b. Create an application that allows a user to enter values for an array of seven Salesperson objects. Offer the user the choice of displaying the objects in order by either ID number or sales value. Save the application as SalespersonSort.java.
Explanation / Answer
public class Salesperson {
private int id;
private double saleAmount;
public Salesperson(int id, double saleAmount) {
super();
this.id = id;
this.saleAmount = saleAmount;
}
public int getId() {
return id;
}
public double getSaleAmount() {
return saleAmount;
}
public void setId(int id) {
this.id = id;
}
public void setSaleAmount(double saleAmount) {
this.saleAmount = saleAmount;
}
@Override
public String toString() {
return getId()+", "+getSaleAmount();
}
}
###############
import java.util.Scanner;
public class SalespersonSort {
static void sortById(Salesperson arr[])
{
int n = arr.length;
// One by one move boundary of unsorted subarray
for (int i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j].getId() < arr[min_idx].getId())
min_idx = j;
// Swap the found minimum element with the first
// element
Salesperson temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
static void sortByAmount(Salesperson arr[])
{
int n = arr.length;
// One by one move boundary of unsorted subarray
for (int i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j].getSaleAmount() < arr[min_idx].getSaleAmount())
min_idx = j;
// Swap the found minimum element with the first
// element
Salesperson temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
Salesperson[] persons = new Salesperson[7];
Scanner sc = new Scanner(System.in);
System.out.println("Enter detail of 7 sales person: ");
int i=0;
while(i < 7) {
System.out.println("Enter id and name of "+(i+1)+" sale person: ");
int id =sc.nextInt();
double amt = sc.nextDouble();
persons[i] = new Salesperson(id, amt);
}
System.out.println("1. sort by id 2. sort by amount: ");
int op = sc.nextInt();
if(op == 1) {
sortById(persons);
}else if(op == 2){
sortByAmount(persons);
}else{
System.out.println("invalid option");
}
for(Salesperson s : persons){
System.out.println(s);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.