Answer:
See explaination
Explanation:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Donor {
public static void main(String[] args){
int idNumbers[] = new int[50]; //created two array each of 50 size
int donations[] = new int[50];
int donorCount=readFile(idNumbers, donations); //calling readfile function
System.out.println("--------------------Original record--------------------");
printDetails(idNumbers,donations,donorCount); //printing details
sortByDonorId(idNumbers,donations,donorCount);
System.out.println("--------------------Sort by donor id--------------------");
printDetails(idNumbers,donations,donorCount);
sortByDonation(idNumbers,donations,donorCount);
System.out.println("--------------------Sort by donation amount--------------------");
printDetails(idNumbers,donations,donorCount);
}
private static void sortByDonation(int[] idNumbers, int[] donations, int donorCount) {
for(int i=0;i<=donorCount;i++){
for(int j=i+1;j<=donorCount;j++){
if(donations[i]>donations[j]){ //comparison based on donations
int temp = idNumbers[i];
idNumbers[i] = idNumbers[j];
idNumbers[j] = temp;
temp = donations[i];
donations[i] = donations[j];
donations[j] = temp;
}
}
}
}
private static void sortByDonorId(int[] idNumbers, int[] donations, int donorCount) {
for(int i=0;i<=donorCount;i++){
for(int j=i+1;j<=donorCount;j++){
if(idNumbers[i]>idNumbers[j]){ //comparison based on donor number
int temp = idNumbers[i];
idNumbers[i] = idNumbers[j];
idNumbers[j] = temp;
temp = donations[i];
donations[i] = donations[j];
donations[j] = temp;
}
}
}
}
public static void printDetails(int[] idNumbers, int[] donations, int donorCount){
System.out.printf("%-5s%s"," ","Donor information"); //using printf for format output
System.out.printf("\n%-20s%-20s","ID number","donations");
for(int i=0;i<=donorCount;i++){
System.out.printf("\n%-20s%-20s",idNumbers[i],donations[i]);
}
System.out.println();
}
public static int readFile(int idNumbers[],int donations[]){
File file = new File("input.txt"); //reading data from this file
Scanner reader;
int donorIndex=-1; //keep track of number of records
try {
reader = new Scanner(file);
while(reader.hasNext()){
donorIndex++;
String line = reader.nextLine();
idNumbers[donorIndex] = Integer.parseInt(line.split(" ")[0]); //spliting line by space,0 is idnumber
donations[donorIndex] = Integer.parseInt(line.split(" ")[1]); //spliting line by space,1 is donations
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return donorIndex;
}
}