// INSTRUCTIONS: 1. Complete methods, sigma, printPerfect, and listAmicable as specified
// 2. Complete isPrime as specified
public class Sigma{
static String TAB = "\t";
public static void main(String[] args) {
sigmaDriver(20);
printPerfectDriver(9000);
listAmicableDriver(100000);
isPrimeDriver(40);
} //== main
public static int sigma(int n) {
// precondition: n > 0
// postcondition: returns sum of n's proper divisor's (including 1)
//------------------------------------------------------------------
return -77;
} //=== sigma
public static void printPerfect(int n) {
// precondition: n > 0
// postcondition: prints all the perfect #s from 1 to n
//--------------------------------------------------------------------
}//=== printPerfect
public static void listAmicable(int n) {
// precondition: n > 0
// postcondition: prints all amicable pairs in [1, n].
// Note: if 220 and 284 are printed, 282 and 220 shouldn't be!!
//--------------------------------------------------------------------
}//=== listAmicable
public static boolean isPrime(int n) {
// precondition: n > 0
// postcondition: return true if n is prime, otherwise return false
//----------------------------------------------------------------------
return false;
} //=== isPrime
static void sigmaDriver(int n) {
MyTerminal.cls(); //clear the screen
System.out.println(TAB + TAB + TAB + "sigma method driver");
for (int k = 2; k <= n; k++) {
System.out.println("sigma(" + k + ") = " + TAB + sigma(k));
}
wait2();
}//===sigmaDriver
static void printPerfectDriver(int last) {
MyTerminal.cls(); //clear the screen
System.out.println(TAB + TAB + TAB + "printPerfect method driver");
System.out.println("\nprinting all perfect numbers from 1 to " + last);
System.out.println("Note: The first 5 perfect numbers are 6, 28, 496, 8128, 33550396\n");
printPerfect(9000);
wait2();
} //=== printPerfectDriver
static void listAmicableDriver(int last) {
MyTerminal.cls(); //clear the screen
System.out.println(TAB + TAB + TAB + "listAmicable method driver");
System.out.println("\nprinting all amicable pairs from 1 to " + last);
System.out.println("Note: If last = 100000, there are 13 amicable pairs, the last being (79750, 88730)\n");
listAmicable(last);
wait2();
} //=== listAmicableDriver
static void isPrimeDriver(int last) {
MyTerminal.cls(); //clear the screen
System.out.println(TAB + TAB + TAB + "isPrime method driver");
System.out.println("\nprinting and summing all primes from 2 to " + last);
System.out.println("Note: There are 12 primes in [2,40] and their sum is 197\n");
int count = 0, sum = 0;
for (int k = 2; k <= last; k++) {
if ( isPrime(k) ) {
count += 1; sum += k;
System.out.println(count + TAB + k);
}
}
System.out.println("\nsum = " + sum);
wait2();
} //=== listAmicableDriver
static void wait2() {
MyTerminal.readString("\nPress <ENTER> __twice__ to continue...");
}
}//== Sigma
//==================================================================================================================
// FILE: RadixOps.java
// INSTRUCTIONS: 1. Complete decToBin & decToOct as specified
// 2. Implement a binToDec and binToDecDriver
public class RadixOps{
static String TAB = "\t";
public static void main(String[] args) {
decToBinDriver();
decToOctDriver();
} //== main
public static String decToBin(int n) {
// precondition: n > 0
// postcondition: returns string returning n in binary form
//------------------------------------------------------------------
return "XXX";
} //=== decToBin
public static String decToOct(int n) {
// precondition: n > 0
// postcondition: returns string returning n in octal form
//------------------------------------------------------------------
return "XXX";
} //=== decToOct
static void decToBinDriver() {
String[] bin = {"0", "1", "10", "11", "100", "101", "110", "111", "1000", "1001", "1010",
"1011", "1100", "1101", "1110", "1111", "10000", "10001", "10010", "10011", "10100"};
MyTerminal.cls();
System.out.println(TAB + TAB + TAB + "decToBin driver");
System.out.println("\n" + TAB + "decimal" + TAB + TAB + "binary" + TAB + TAB + "decToBin");
for (int k = 0; k < bin.length; k++) {
System.out.println(TAB + k + TAB + TAB + bin[k] + TAB + TAB + decToBin(k));
}
wait2();
}//===decToBinDriver
static void decToOctDriver() {
String[] bin = {"0", "1", "2", "3", "4", "5", "6", "7", "10", "11", "12",
"13", "14", "15", "16", "17", "20", "21", "22", "23", "24"};
MyTerminal.cls();
System.out.println(TAB + TAB + TAB + "decToOct driver");
System.out.println("\n" + TAB + "decimal" + TAB + TAB + "octal" + TAB + TAB + "decToOct");
for (int k = 0; k < bin.length; k++) {
System.out.println(TAB + k + TAB + TAB + bin[k] + TAB + TAB + decToOct(k));
}
wait2();
}//===decToOctDriver
static void wait2() {
MyTerminal.readString("\nPress <ENTER> __twice__ to continue...");
}
}//== RadixOps
//==================================================================================================================
//hexadecimal methods
//INSTRUCTIONS: 1. Insert calls to decToHexDriver and hexToDecDriver in main
// 2. Implement decToHex before implementing hexToDec
public static String decToHex(int n) {
// precondition: n > 0
// postcondition: returns string representing n in hexadecimal form
//------------------------------------------------------------------
return "XXXX";
} //=== decToHex
public static int hexToDec(String hex) {
// precondition: hex represents a valid hexadecimal number
// postcondition: returns returns numerical value that hex represents
//------------------------------------------------------------------
return -77;
} //=== hexTodec
static void decToHexDriver() {
String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "10", "11", "12", "13", "14",
"15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F", "20", "21", "22", "23", "24", "25", "26", "27"};
MyTerminal.cls();
System.out.println(TAB + TAB + TAB + "decToHex driver");
System.out.println("\n" + TAB + "decimal" + TAB + TAB + "hex" + TAB + TAB + "decToHex");
for (int k = 0; k < hex.length; k++) {
System.out.println(TAB + k + TAB + TAB + hex[k] + TAB + TAB + decToHex(k));
if ( k % 20 == 0 && k != 0 || k == hex.length -1 ) {
wait2();
System.out.println("\n" + TAB + TAB + TAB + "decToHex driver");
System.out.println("\n" + TAB + "decimal" + TAB + TAB + "hex" + TAB + TAB + "decToHex");
}
}
int n = 256;
System.out.println(TAB + n + TAB + TAB + "100" + TAB + TAB + decToHex(n)); n *= 2;
System.out.println(TAB + n + TAB + TAB + "200" + TAB + TAB + decToHex(n)); n++;
System.out.println(TAB + n + TAB + TAB + "201" + TAB + TAB + decToHex(n)); n += 16;
System.out.println(TAB + n + TAB + TAB + "211" + TAB + TAB + decToHex(n)); n += 16;
System.out.println(TAB + n + TAB + TAB + "221" + TAB + TAB + decToHex(n)); n += 16;
System.out.println(TAB + n + TAB + TAB + "231" + TAB + TAB + decToHex(n)); n = 16*16*16;
System.out.println(TAB + n + TAB + TAB + "1000" + TAB + TAB + decToHex(n)); n *= 16;
System.out.println(TAB + n + TAB + TAB + "10000" + TAB + TAB + decToHex(n)); n *= 16;
System.out.println(TAB + n + TAB + TAB + "100000" + TAB + TAB + decToHex(n));
wait2();
}//===decToOctDriver
static void hexToDecDriver() {
MyTerminal.cls();
System.out.println(TAB + TAB + TAB + "hexToDec driver: REQUIRES A VALID decToHex METHOD");
System.out.println("\n" + TAB + "hex" + TAB + TAB + "decimal" + TAB + TAB + "hexToDec");
final int LAST = 41;
for (int k = 0; k < LAST; k++) {
System.out.println(TAB + decToHex(k) + TAB + TAB + k + TAB + TAB + hexToDec(decToHex(k)));
if ( k % 20 == 0 && k != 0 && k != LAST - 1) {
wait2();
System.out.println("\n" + TAB + TAB + TAB + "hexToDec driver: REQUIRES A VALID decToHex METHOD");
System.out.println("\n" + TAB + "hex" + TAB + TAB + "decimal" + TAB + TAB + "hexToDec");
}
}
wait2();
}//===decToOctDriver
//==============================================================================================================================
//FILE: ArrayOps.java
// INSTRUCTIONS: 1. Implement findMinMax, findStats, searchList
// 2. Implement shiftRight, shiftLeft, insertFront,
// 3. Implement deleteFront, insertOdereded
// 4. Implement deleteOrdered, sortList
public class ArrayOps {
static String TAB = "\t";
public static void main(String[] args) {
int[] numList = new int[16];
loadArray(numList);
char choice;
for (;;) {
MyTerminal.cls();
printArray(numList);
choice = menu();
switch ( choice ) {
case '1': findMinMax(numList); break;
case '2': findStats(numList); break;
case '3': searchDriver(numList); break;
case '4': // fall thru to case '5'
case '5': shiftDriver(numList, choice); break;
case '6': // fall thru to case '7'
case '7': unorderedDriver(numList, choice); break;
case '8': orderedDriver(numList); break;
case '9': sortList(numList); break;
case 0: break;
}//=== switch
if ( choice == '0' ) break;
else {
MyTerminal.readString("\nPress <ENTER> to continue...");
}
}
} //=== main
static void findMinMax(int[] list) {
// precondition: list is initialized
//postcondition: min and max value in list are printed
int min = 77, max = -77;
System.out.println("min value = " + min + "\nmax value = " + max);
}
static void findStats(int[] list) {
// precondition: list is initialized
//postcondition: mean and std deviation are printed
double mean = -77, stdDev = -77;
System.out.println("mean = " + mean + "\nstandard deviation = " + stdDev);
}
static int searchList(int[] list, int value) {
// precondition: list is initialized
//postcondition: if value is in list, index position is returned, else -1 returned
return -77;
}//====
static void shiftRight(int[] X, int pos) {
// precond: X is initialized, pos < X.length
//postcond: all X[k] for k in [pos, list.length-2] shifted one position toward X.length-1
//EXAMPLE: If X = [11, 22, 33, 44, 55], after shiftRight(X, 1) X = [11, 22, 22, 33, 44]
} //=== shiftRight
public static void shiftLeft(int[] X, int pos) {
// precond: X is initialized, pos < X.length //postcond: all X[k] for k in [pos, X.length-1] are shifted one position toward index 0 //EXAMPLE: If X = [11, 22, 33, 44, 55], after shiftLeft(X, 1) X = [11, 33, 44, 55, 55]
}//=== shiftLeft
static void insertFront(int[] list, int value) {
// precondition: list is initialized, shiftRight & shiftLeft are available
//postcondition: all elements in list[1...length-2] shifted one index postion to the left
}//=== insertFront
static int deleteFront(int[] list) {
// precondition: list is initialized, shiftRight & shiftLeft are available
//postcondition: all elements in list[1...length-1] shifted one index postion to the left and value at front returned
return -77;
}//=== deleteFront
static void insertOrdered(int[] list, int value) {
// precondition: list is initialized, shiftRight & shiftLeft are available
//postcondition: value is inserted in order, all elements from insertion position to the end are shifted right
//EXAMPLE: If X = [11, 22, 33, 44, 55], after InsertOrdered(X, 15) X = [11, 15, 22, 33, 44]
}//=== insertOrdered
static void deleteOrdered(int[] X, int val) {
//precondition: shiftRight and shiftLeft are available
//postcondition: if val not found, no change; otherwise see example
//EXAMPLE: If X = [11, 22, 33, 44, 55], after deleteOrdered(X, 22) X = [11, 33, 44, 55, 55]
}//=== deleteOrdered
static void sortList(int[] list) {
// precondition: list is initialized
//postcondition: all elements in list are in ascending order
// replace this with selection sort when instructed
java.util.Arrays.sort(list);
}//=== sortList
//----------------------------------------------------------------------------------
static void loadArray(int[] list) {
String x = "QEPHCANIUSXYWDMGB";
for (int k = 0; k < list.length; k++) {
list[k] = x.charAt(k);
}
}//=== loadArray
static void printArray(int[] list) {
System.out.println(TAB + "INDEX" + TAB + "VALUE");
for (int k = 0; k < list.length; k++) {
System.out.println(TAB + k + TAB + list[k]);
}
}//=== loadArray
static char menu() {
final String INDENT = TAB + TAB + TAB + TAB;
String[] items = {
" ARRAY OPERATIONS",
"---------------------------------------------------------",
"Find maximum/minimum value..............................1",
"Get statistics (mean, std dev)..........................2",
"Search for an item......................................3",
"Shift items one index position to the right.............4",
"Shift items one index position to the left..............5",
"Insert item at front (losing last item).................6",
"Delete item at front ...................................7",
"Insert/Delete item (ordered list).......................8",
"Sort list...............................................9",
"Quit....................................................0",
"Selection================> "
};
for (int k = 0; k < items.length-1; k++) {
System.out.println(INDENT + items[k]);
}
char ch;
for (;;) {
String s = MyTerminal.readString(INDENT + items[items.length-1]);
if ( s.length() == 0 ) ch = 'Z';
else ch = s.charAt(0);
if ( ch >= '0' && ch <= '9' ) return ch;
System.out.println("ERROR: invalid response\n");
} //===for
}//=== menu
static void shiftDriver(int[] list, int ch) {
System.out.println((ch == '3' ?"SHIFTING RIGHT\n" :"SHIFTING LEFT\n"));
int pos = MyTerminal.readInt("Enter index position where shifting begins: ");
if ( ch == '4' ) shiftRight(list, pos);
else shiftLeft(list, pos);
}//=== shiftDriver
static void searchDriver(final int[] list) {
int val = MyTerminal.readInt("Enter value to be searched: ");
int pos = searchList(list, val);
if ( pos < 0 ) {
System.out.println(val + " not found.");
}
else {
System.out.println(val + " found at index position " + pos);
}
}//=== searchDriver
static void unorderedDriver(final int[] list, char ch) {
if ( ch == '6' ) {
int val = MyTerminal.readInt("Enter value of item to insert: ");
insertFront(list, val);
}
else {
int val = deleteFront(list);
System.out.println("Element whose value = " + val + " removed.");
}
}//=== unorderedDriver
static void orderedDriver(int[] list) {
int val = MyTerminal.readInt("Enter value of item: ");
for (;;) {
String s = MyTerminal.readString("Insert or Delete (I/D): ");
if ( s.length() > 0 ) {
char ch = s.charAt(0);
if ( ch >= 'a' && ch <= 'z' )
ch = (char)(ch - ('a' - 'A'));
if ( ch == 'I' ) {
insertOrdered(list, val); return;
}
else if ( ch == 'D' ) {
deleteOrdered(list, val); return;
}
} //== if s.length
}//===for
}//=== orderedDriver
} // === end of ArrayOps ===============================================================================================
//Replacement for
orderedDriver in ArrayOps.java
static void orderedDriver(int[] list) {
int val = MyTerminal.readInt("Enter value of item: ");
for (;;) {
String s = MyTerminal.readString("Insert or Delete (I/D): ");
if ( s.length() > 0 ) {
char ch = s.charAt(0);
if ( ch >= 'a' && ch <= 'z' )
ch = (char)(ch - ('a' - 'A'));
if ( ch == 'I' ) {
insertOrdered(list, val); return;
}
else if ( ch == 'D' ) {
deleteOrdered(list, val); return;
}
} //== if s.length
}//===for
}//=== orderedDriver
//===========================================================================
//FILE: ArrayCopy.java
public class ArrayCopy {
static String TAB = "\t";
public static void main(String[] args) {
int[] A = {22, 33, 44, 55, 66}, B = {77, 88, 99, 110, 121},
C = {77, 88, 99, 110, 121};
copyArray1Driver(A, B, "Copying A[] to B[] with copyArray1");
System.out.println("\nFinal values in B:");
printArray(B);
MyTerminal.readString("Press <ENTER> to continue...");
B = C;
copyArray2Driver(A, B, "Copying A[] to B[] with copyArray2");
System.out.println("Final values in B:");
printArray(B);
} //=== main
public static void copyArray1(int[] X, int[] Y) {
Y = new int[X.length];
for (int k = 0; k < X.length; k++)
Y[k] = X[k];
}
public static void copyArray2(int[] X, int[] Y) {
int len;
if ( X.length >= Y.length ) len = X.length;
else len = Y.length;
for (int k = 0; k < len; k++)
Y[k] = X[k];
}
public static int[] copyArray3(int[] X) {
int[] A = new int[X.length];
for (int k = 0; k < X.length; k++)
A[k] = X[k];
return A;
}
//------------------------------------------------------------------------
static void loadArray(int[] list) {
String x = "QEPHCANIUSXYWDMGB";
for (int k = 0; k < list.length; k++) {
list[k] = x.charAt(k);
}
}//=== loadArray
static void printArray(int[] list) {
System.out.println(TAB + "INDEX" + TAB + "VALUE");
for (int k = 0; k < list.length; k++) {
System.out.println(TAB + k + TAB + list[k]);
}
}//=== loadArray
static void copyArray1Driver(int[] X, int[] Y, final String msg) {
int len = X.length;
if ( Y.length > len ) len = Y.length;
MyTerminal.cls();
System.out.println(msg + "\n");
System.out.println("Before copyArray1(A, B): ");
System.out.println("INDEX" + TAB + "A[k]" + TAB + "B[k]");
for (int k = 0 ; k < len; k++) {
System.out.println(TAB + k + TAB + X[k] + TAB + Y[k]);
}
copyArray1(X, Y);
System.out.println("\nAfter copyArray1(A, B): ");
System.out.println("INDEX" + TAB + "A[k]" + TAB + "B[k]");
for (int k = 0 ; k < len; k++) {
System.out.println(TAB + k + TAB + X[k] + TAB + Y[k]);
}
MyTerminal.readString("Press <ENTER> to continue...");
} //=== copyArray1Driver
static void copyArray2Driver(int[] X, int[] Y, final String msg) {
int len = X.length;
if ( Y.length > len ) len = Y.length;
MyTerminal.cls();
System.out.println(msg + "\n");
System.out.println("Before copyArray2(A, B): ");
System.out.println("INDEX" + TAB + "A[k]" + TAB + "B[k]");
for (int k = 0 ; k < len; k++) {
System.out.println(TAB + k + TAB + X[k] + TAB + Y[k]);
}
copyArray2(X, Y);
System.out.println("\nAfter copyArray2(A, B): ");
System.out.println("INDEX" + TAB + "A[k]" + TAB + "B[k]");
for (int k = 0 ; k < len; k++) {
System.out.println(TAB + k + TAB + X[k] + TAB + Y[k]);
}
MyTerminal.readString("Press <ENTER> to continue...");
} //=== copyArray2Driver
} //=== ArrayCopy
// === end of ArrayCopy =============================================================================================
//FILE: ArrayOps2.java
// INSTRUCTIONS: 1. Implement findMinMax, findStats, searchList
// 2. Implement shiftRight, shiftLeft, insertFront,
// 3. Implement deleteFront, insertOdereded
// 4. Implement deleteOrdered, sortList
import java.util.Random;
public class ArrayOps2 {
static String TAB = "\t";
public static void main(String[] args) {
Employee[] X = loadArray();
char choice;
for (;;) {
MyTerminal.cls();
printArray(X);
choice = menu();
switch ( choice ) {
case '1': findMinMax(X); break;
case '2': findStats(X); break;
case '3': searchDriver(X); break;
case '4': // fall thru to case '5'
case '5': shiftDriver(X, choice); break;
case '6': // fall thru to case '7'
case '7': unorderedDriver(X, choice); break;
case '8': orderedDriver(X); break;
case '9': sortList(X); break;
case 0: break;
}//=== switch
if ( choice == '0' ) break;
else {
MyTerminal.readString("\nPress <ENTER> to continue...");
}
}
} //=== main
static void findMinMax(Employee[] list) {
// precondition: list is initialized
//postcondition: min and max value in list are printed
int min = 77, max = -77;
System.out.println("min value = " + min + "\nmax value = " + max);
}
static void findStats(Employee[] list) {
// precondition: list is initialized
//postcondition: mean and std deviation are printed
double mean = -77, stdDev = -77;
System.out.println("mean = " + mean + "\nstandard deviation = " + stdDev);
}
static int searchList(Employee[] list, String name) {
// precondition: list is initialized
//postcondition: if value is in list, index position is returned, else -1 returned
return -77;
}
static void shiftRight(Employee[] X, int pos) {
// precond: X is initialized, pos < X.length
//postcond: all X[k] for k in [pos, list.length-2] shifted one position toward X.length-1
//EXAMPLE: If X = [11, 22, 33, 44, 55], after shiftRight(X, 1) X = [11, 22, 22, 33, 44]
} //=== shiftRight
static void shiftLeft(Employee[] X, int pos) {
// precond: X is initialized, pos < X.length
//postcond: all X[k] for k in [pos, X.length-1] are shifted one position toward index 0
//EXAMPLE: If X = [11, 22, 33, 44, 55], after shiftLeft(X, 1) X = [11, 33, 44, 55, 55]
}//=== shiftLeft
static void insertFront(Employee[] list, Employee e) {
// precondition: list is initialized, shiftRight & shiftLeft are available
//postcondition: all elements in list[1...length-2] shifted one index postion to the right
}//=== insertFront
static Employee deleteFront(Employee[] list) {
// precondition: list is initialized, shiftRight & shiftLeft are available
//postcondition: all elements in list[1...length-1] shifted one
// index postion to the left and value at front returned
return list[5];
}//=== deleteFront
static void insertOrdered(Employee[] list, Employee e) {
// precondition: list is initialized, shiftRight & shiftLeft are available
//postcondition: value is inserted in order, all elements from insertion position to the end are shifted right
//EXAMPLE: If X = [11, 22, 33, 44, 55], after InsertOrdered(X, 15) X = [11, 15, 22, 33, 44]
}//=== insertOrdered
static void deleteOrdered(Employee[] list, String name) {
// precondition: list is initialized, shiftRight & shiftLeft are available
//postcondition: item with name is deleted, all elements from
// deletion position to the end are shifted left
}//=== deleteOrdered
static void sortList(Employee[] list) {
// precondition: list is initialized
//postcondition: all elements in list are in ascending order on name field with selection sort
}//=== sortList
//----------------------------------------------------------------------------------
static Employee[] loadArray() {
String[] A = { "Robert", "Beverly", "Leslie", "Morris", "Patrice", "Josephine", "Juanita", "Hoover"};
String[] B = { "Iago", "Othello", "Brooke", "William", "Albert", "Wolfgang", "Felix", "Cyrus"};
Employee[] E = new Employee[2*A.length];
Random rGen = new Random(29L);
for (int k = 0; k < A.length; k++) {
E[k] = new Employee(A[k] + " " + B[k], 1000*rGen.nextInt(10) + 40000, 1960 + rGen.nextInt(21));
E[E.length - 1 - k] = new Employee(B[k] + " " + A[k], 1000*rGen.nextInt(10) + 40000, 1960 + rGen.nextInt(15));
}
return E;
}//=== loadArray
static void printArray(Employee[] list) {
System.out.println(TAB + "INDEX" + TAB + "VALUE");
for (int k = 0; k < list.length; k++) {
System.out.println(TAB + k + TAB + list[k]);
}
}//=== loadArray
static char menu() {
final String INDENT = TAB + TAB + TAB + TAB;
String[] items = {
" ARRAY OPERATIONS",
"---------------------------------------------------------",
"Find maximum/minimum value..............................1",
"Get statistics (mean, std dev)..........................2",
"Search for an item......................................3",
"Shift items one index position to the right.............4",
"Shift items one index position to the left..............5",
"Insert item at front (losing last item).................6",
"Delete item at front ...................................7",
"Insert/Delete item (ordered list).......................8",
"Sort list...............................................9",
"Quit....................................................0",
"Selection================> "
};
System.out.println();
for (int k = 0; k < items.length-1; k++) {
System.out.println(INDENT + items[k]);
}
char ch;
for (;;) {
String s = MyTerminal.readString(INDENT + items[items.length-1]);
if ( s.length() == 0 ) ch = 'Z';
else ch = s.charAt(0);
if ( ch >= '0' && ch <= '9' ) return ch;
System.out.println("ERROR: invalid response\n");
} //===for
}//=== menu
static void shiftDriver(Employee[] list, int ch) {
System.out.println((ch == '3' ?"SHIFTING RIGHT\n" :"SHIFTING LEFT\n"));
int pos = MyTerminal.readInt("Enter index position where shifting begins: ");
if ( ch == '4' ) shiftRight(list, pos);
else shiftLeft(list, pos);
}//=== shiftDriver
static void searchDriver(final Employee[] list) {
String name = MyTerminal.readString("Enter name to be searched: ");
int pos = searchList(list, name);
if ( pos < 0 ) {
System.out.println(name + " not found.");
}
else {
System.out.println(name + " found at index position " + pos);
}
}//=== searchDriver
static void unorderedDriver(final Employee[] list, char ch) {
if ( ch == '6' ) {
String name = MyTerminal.readString("Enter name of employee: ");
double salary = MyTerminal.readDouble("Enter salary of employee: ");
int YOB = MyTerminal.readInt("Enter year of birth of employee: ");
Employee e = new Employee(name, salary, YOB);
insertFront(list, e);
}
else {
Employee e = deleteFront(list);
System.out.println("This element was removed: " + e);
}
}//=== unorderedDriver
static void orderedDriver(Employee[] list) {
String name = MyTerminal.readString("Enter name of employee: ");
for (;;) {
String s = MyTerminal.readString("Insert or Delete (I/D): ");
if ( s.length() > 0 ) {
char ch = s.charAt(0);
if ( ch >= 'a' && ch <= 'z' )
ch = (char)(ch - ('a' - 'A'));
if ( ch == 'I' ) {
double salary = MyTerminal.readDouble("Enter salary of employee: ");
int YOB = MyTerminal.readInt("Enter year of birth of employee: ");
Employee e = new Employee(name, salary, YOB);
insertOrdered(list, e); return;
}
else if ( ch == 'D' ) {
deleteOrdered(list, name); return;
}
} //== if s.length
}//===for
}//=== orderedDriver
} // === end of ArrayOps2 class
class Employee {
private final String name;
private double salary;
private int YOB;
public Employee(String name, double salary, int YOB) {
this.name = name; this.salary = salary; this.YOB = YOB;
}
public Employee(String name) {
this(name, -77.77, 0);
}
public Employee(String name, int YOB) {
this(name, -77.77, YOB);
System.out.println(YOB);
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public String toString() {
return getClass().getName() + "[name= " + name + ", salary = " + salary
+ ", YOB= " + YOB + "]";
}
public boolean equals(Employee e) {
if ( e == null ) return false;
else return name.equals(e.name) && salary == e.salary && YOB == e.YOB;
}
public void raise(double amt) {
if ( amt <= 0.1 * salary )
salary += amt;
}
} // === end of Employee class
//============================= end of ArrayOps2 ===========================
//FILE: Complex.java
// INSTRUCTIONS:
// 1. Implement object and static versions of mult, raise, and divide that were assigned for HW last wwek
// 2. Implement object method raise such that A.raise(n) returns A^n, where n >= 0
// 3. Run your implementation and test it against the correct output shown below:
/*
Testing raise implementations: raising (1 - i)
(1.0 - 1.0i)^0 = 1.0 + 0i
(1.0 - 1.0i)^1 = 1.0 - 1.0i
(1.0 - 1.0i)^2 = -2.0i
(1.0 - 1.0i)^3 = -2.0 - 2.0i
(1.0 - 1.0i)^4 = -4.0 + 0i
(1.0 - 1.0i)^5 = -4.0 + 4.0i
(1.0 - 1.0i)^6 = 8.0i
(1.0 - 1.0i)^7 = 8.0 + 8.0i
(1.0 - 1.0i)^8 = 16.0 + 0i
*/
public class Complex {
private double a, b, AV;
public Complex(double a2, double b2) {
a = a2; b = b2; setAV();
}
public Complex() {
this(0, 0);
}
public double getA() { return a; }
public double getB() { return b; }
public double getAV() { return AV; }
public String stdForm() {
if ( Math.abs(a) < 1e-6 ) {
return b + "i";
}
else if ( Math.abs(b) < 1e-6 ) return a + " + 0i";
else if ( b > 0 ) return a + " + " + b + "i";
else return a + " - " + -b + "i";
}
public boolean equals(Complex other) {
return other != null && ( a == other.a && b == other.b);
}
public String toString() {
return getClass().getName() + "[a= " + a + ", b= " + b
+ ", AV= " + AV + "]";
}
public void setA(double a2) {
a = a2; setAV();
}
public void setB(double b2) {
b = b2; setAV();
}
public Complex add(Complex c) {
return new Complex(a + c.a, b + c.b);
}
public Complex mult(Complex c) {
return new Complex();
}
public Complex recip() {
return new Complex();
}
public Complex divide(Complex c) {
return new Complex();
}
public Complex raise(int exp) {
return new Complex();
}
private void setAV() {
AV = Math.sqrt(a*a + b*b);
}
public static Complex add(Complex X, Complex Y) {
return X.add(Y);
}
public static Complex mult(Complex X, Complex Y) {
return new Complex();
}
public static Complex recip(Complex c) {
return new Complex();
}
public static Complex divide(Complex c, Complex d) {
return new Complex();
}
static String TAB = "\t";
public static void main(String[] args) {
multDriver();
divideDriver();
raiseDriver();
} //=== main
static void multDriver() {
Complex A = new Complex(3, -4), B = new Complex(-12, 5), C = new Complex(1, 0);
MyTerminal.cls();
System.out.println("Testing mult() and recip() implementations\n");
System.out.println("A = " + A.stdForm() + TAB + "B = " + B.stdForm());
System.out.println("\n" + parens(A) + " * " + parens(B) + " = -16 + 63i");
System.out.println("Testing object method: A.mult(B) = " + A.mult(B).stdForm());
System.out.println("Testing static method: mult(A, B) = " + mult(A, B).stdForm());
B = C;
System.out.println("\n" + parens(A) + " * " + parens(B) + " = " +
A.stdForm());
System.out.println("Testing object method: A.mult(B) = " + A.mult(B).stdForm());
System.out.println("Testing static method: mult(A, B) = " + mult(A, B).stdForm());
B = A.recip();
System.out.println("\nTesting recip() implementations (mult must work):");
System.out.println("A = " + A.stdForm() + TAB + "A.recip() = " + A.recip().stdForm());
System.out.println("Testing object method: mult(A, A.recip()) = " + mult(A, A.recip()).stdForm());
System.out.println("Testing static method: mult(A, recip(A)) = " + mult(A, recip(A)).stdForm());
pause();
}
static void divideDriver() {
Complex A = new Complex(-12, 5), B = new Complex(3, -4), C = new Complex(1, 0);
MyTerminal.cls();
System.out.println("Testing divide implementations\n");
System.out.println("A = " + A.stdForm() + TAB + "B = " + B.stdForm());
System.out.println("\n" + parens(A) + " / " + parens(B) + " = -2.24 - 1.32i");
System.out.println("Testing object method: A.divide(B) = " + A.divide(B).stdForm());
System.out.println("Testing static method: divide(A, B) = " + divide(A, B).stdForm());
System.out.println("\n" + parens(A) + " / " + parens(A) + " = 1 + 0i");
System.out.println("Testing object method: A.divide(A) = " + A.divide(A).stdForm());
System.out.println("Testing static method: divide(A, A) = " + divide(A, A).stdForm());
pause();
}
static void raiseDriver() {
Complex X = new Complex(1, -1);
MyTerminal.cls();
System.out.println("Testing raise implementations: raising (1 - i)\n");
for (int k = 0; k <= 8; k++) {
Complex Y = X.raise(k);
System.out.println( parens(X) + "^" + k + " = " + Y.stdForm());
}
} //=== raiseDriver
static void pause() {
MyTerminal.readString("Press <ENTER>...");
}
static String parens(Complex c) {
return "(" + c.stdForm() + ")";
}
} //======= end of Complex class =====================
//FILE: Complex2.java
// This class implements the Comparable interface
// 1. implements Comparable inserted after public class Complex2
// 2. public int compareTo method satisfies the Comparable interface "contract"
// 3. compareToDriver uses java.util.Arrays.sort method which depends upon compareTo method
// to achieve its task
import java.util.*;
public class Complex2 implements Comparable {
private double a, b, AV;
public Complex2(double a2, double b2) {
a = a2; b = b2; setAV();
}
public Complex2() {
this(0, 0);
}
public double getA() { return a; }
public double getB() { return b; }
public double getAV() { return AV; }
public String stdForm() {
if ( Math.abs(a) < 1e-6 ) {
return b + "i";
}
else if ( Math.abs(b) < 1e-6 ) return a + " + 0i";
else if ( b > 0 ) return a + " + " + b + "i";
else return a + " - " + -b + "i";
}
public boolean equals(Complex2 other) {
return other != null && ( a == other.a && b == other.b);
}
public String toString() {
return getClass().getName() + "[a= " + a + ", b= " + b
+ ", AV= " + AV + "]";
}
public int compareTo (Object other) {
// precond: Object is a Complex2 object
//postcond: returns 1 when AV > ((Complex2)other).AV
// returns -1 when AV < ((Complex2)other).AV
// returns 0 when |AV -((Complex2)other).AV| <= 1e-8
double diff = AV - ((Complex2)other).getAV();
if ( Math.abs(diff) < 1e-8 ) diff = 0.0;
if ( diff > 0.0 ) return 1;
else if ( diff < 0.0 ) return -1;
else return 0;
}
public void setA(double a2) {
a = a2; setAV();
}
public void setB(double b2) {
b = b2; setAV();
}
public Complex2 add(Complex2 c) {
return new Complex2(a + c.a, b + c.b);
}
public Complex2 mult(Complex2 c) {
return new Complex2(a * c.a - b * c.b, a * c.b + c.a * b);
}
public Complex2 recip() {
return new Complex2(a/(a*a + b*b), -b/(a*a + b*b));
}
public Complex2 divide(Complex2 c) {
return mult(c.recip());
}
public Complex2 raise(int exp) {
Complex2 product = new Complex2(1, 0);
for (int k = 1; k <= exp; k++) {
product = mult(product);
}
return product;
}
private void setAV() {
AV = Math.sqrt(a*a + b*b);
}
public static Complex2 add(Complex2 X, Complex2 Y) {
return X.add(Y);
}
public static Complex2 mult(Complex2 X, Complex2 Y) {
return X.mult(Y);
}
public static Complex2 recip(Complex2 c) {
return c.recip();
}
public static Complex2 divide(Complex2 c, Complex2 d) {
return c.mult(d.recip());
}
static String TAB = "\t";
public static void main(String[] args) {
multDriver();
divideDriver();
raiseDriver();
compareToDriver();
} //=== main
static void multDriver() {
Complex2 A = new Complex2(3, -4), B = new Complex2(-12, 5), C = new Complex2(1, 0);
MyTerminal.cls();
System.out.println("Testing mult() and recip() implementations\n");
System.out.println("A = " + A.stdForm() + TAB + "B = " + B.stdForm());
System.out.println("\n" + parens(A) + " * " + parens(B) + " = -16 + 63i");
System.out.println("Testing object method: A.mult(B) = " + A.mult(B).stdForm());
System.out.println("Testing static method: mult(A, B) = " + mult(A, B).stdForm());
B = C;
System.out.println("\n" + parens(A) + " * " + parens(B) + " = " +
A.stdForm());
System.out.println("Testing object method: A.mult(B) = " + A.mult(B).stdForm());
System.out.println("Testing static method: mult(A, B) = " + mult(A, B).stdForm());
B = A.recip();
System.out.println("\nTesting recip() implementations (mult must work):");
System.out.println("A = " + A.stdForm() + TAB + "A.recip() = " + A.recip().stdForm());
System.out.println("Testing object method: mult(A, A.recip()) = " + mult(A, A.recip()).stdForm());
System.out.println("Testing static method: mult(A, recip(A)) = " + mult(A, recip(A)).stdForm());
pause();
}
static void divideDriver() {
Complex2 A = new Complex2(-12, 5), B = new Complex2(3, -4), C = new Complex2(1, 0);
MyTerminal.cls();
System.out.println("Testing divide implementations\n");
System.out.println("A = " + A.stdForm() + TAB + "B = " + B.stdForm());
System.out.println("\n" + parens(A) + " / " + parens(B) + " = -2.24 - 1.32i");
System.out.println("Testing object method: A.divide(B) = " + A.divide(B).stdForm());
System.out.println("Testing static method: divide(A, B) = " + divide(A, B).stdForm());
System.out.println("\n" + parens(A) + " / " + parens(A) + " = 1 + 0i");
System.out.println("Testing object method: A.divide(A) = " + A.divide(A).stdForm());
System.out.println("Testing static method: divide(A, A) = " + divide(A, A).stdForm());
pause();
}
static void raiseDriver() {
Complex2 X = new Complex2(1, -1);
MyTerminal.cls();
System.out.println("Testing raise implementations: raising (1 - i)\n");
for (int k = 0; k <= 8; k++) {
Complex2 Y = X.raise(k);
System.out.println( parens(X) + "^" + k + " = " + Y.stdForm());
}
pause();
} //=== raiseDriver
static void compareToDriver() {
MyTerminal.cls();
System.out.println("Testing compareTo implementation\n");
final int MAX = 21;
Random rGen = new Random(17L);
Complex2[] A = new Complex2[10];
for (int k = 0; k < A.length; k++)
A[k] = new Complex2(rGen.nextInt(MAX), rGen.nextInt(MAX));
System.out.println("Array of Complex before sort:");
for (int k = 0; k < A.length; k++)
System.out.println(TAB + k + TAB + A[k]);
java.util.Arrays.sort(A); // will not work unless Complex2 class has a compareTo method!!
System.out.println("Array of Complex after sort:");
for (int k = 0; k < A.length; k++)
System.out.println(TAB + k + TAB + A[k]);
}
static void pause() {
MyTerminal.readString("Press <ENTER>...");
}
static String parens(Complex2 c) {
return "(" + c.stdForm() + ")";
}
} //=== Complex2
//================================================================
//FILE: Employee1.java
// INSTRUCTIONS:
// 1. Study this short program which uses inheritance to create a Manager class
// 2. Run program and notice that the equals method doesn't work for Manager objects
// when bonuses aren't equal
// 3. Implement an equals method for Manager class by overriding Employee equals method
public class Employee1 {
private final String name;
private double salary;
private int YOB;
public Employee1(String name, double salary, int YOB) {
this.name = name; this.salary = salary; this.YOB = YOB;
}
public Employee1(String name) {
this(name, -77.77, 0);
}
public Employee1(String name, int YOB) {
this(name, -77.77, YOB);
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public String toString() {
return getClass().getName() + "[name= " + name +
", salary = " + salary + ", YOB= " + YOB + "]";
}
public boolean equals(Employee1 e) {
if ( e == null ) return false;
else return name.equals(e.name) && salary == e.salary && YOB == e.YOB;
}
public void raise(double amt) {
if ( amt <= 0.1 * salary )
salary += amt;
}
public static final String TAB = "\t";
public static void main(String[] args) {
Employee1[] A = new Employee1[3];
Manager big = new Manager("Stan", 200000, 1970, 4500);
A[0] = big;
A[1] = new Employee1("Bo", 40000, 1980);
A[2] = new Employee1("Mo", 50000, 1975);
//big = A[0]; // syntax error: Manager reference implies more functionality than an Employee object possesses:
// Remember that the superclass has LESS functionality than its subclass!!
System.out.println("\nPrinting Array of Employee objects:");
System.out.println("Note that interpreter uses Manager toString method for A[0] and Employee toString method for A[1] & A[2]\n");
for (int k = 0; k < A.length; k++) {
System.out.println(k + TAB + A[k]);
}
Manager big2 = new Manager("Stan", 200000, 1970, 4500);
Manager big3 = new Manager("Stan", 200000, 1970, -777);
System.out.println("\nTesting: equals method for Manager objects");
System.out.println("TESTING: big.equals(big2):");
System.out.println("big = " + big + "\nbig2 = " + big2 + "\n(big == big2) = " + (big.equals(big2)));
System.out.println("TESTING: big.equals(big3):");
System.out.println("big = " + big + "\nbig3 = " + big3 + "\n(big == big3) = " + (big.equals(big3)));
} //=== main
} // === end of Employee1 class
class Manager extends Employee1 {
private double bonus;
public Manager( String n, double s, int D, double b) {
super(n, s, D);
bonus = b;
}
public double getSalary() {
return super.getSalary() + bonus;
}
public String toString() {
return super.toString() + "[bonus = " + bonus + "]";
}
} // === end of Manager class
//============================ end of Employee1 file ============================
// DrawPrimitive.java
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class DrawPrimitive {
public static final int DEFAULT_WIDTH = 500;
public static final int DEFAULT_HEIGHT = 400;
public static void main(String[] args) {
// Create and initialize JFrame object for 2D graphics
JFrame frame = new JFrame();
frame.setTitle("JFrame class frame");
frame.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// Create an extended JPanel object which contains the 2D graphics
Panel panel = new Panel();
Container contentPane = frame.getContentPane();
contentPane.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
} //=== main
} //=== class DrawPrimitive
class Panel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
double leftX = 100, topY = 100;
double width = 300, height = 200;
g2.setPaint(Color.BLACK);
g2.drawString("Using drawString(String, 0, 30) to paint this message in panel", 0, 30);
// Store four corners for diagonals
Point2D upperLeft = new Point2D.Double(leftX, topY);
Point2D lowerRight = new Point2D.Double(leftX + width - 1, topY + height - 1);
Point2D upperRight = new Point2D.Double(leftX + width - 1, topY);
Point2D lowerLeft = new Point2D.Double(leftX, topY + height - 1);
//===== Draw 10 enclosing red rectangles
final int RECTS = 10;
g2.setPaint(Color.RED);
final int dx = (int)width/RECTS, dy = (int)height/RECTS;
for (int k = 1; k <= RECTS; k ++) {
Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height);
g2.draw(rect);
leftX += dx/2; topY += dy/2; width -= dx; height -= dy;
}
//====== Draw blue diagonals
g2.setPaint(Color.BLUE);
Line2D diag1 = new Line2D.Double(upperLeft, lowerRight);
Line2D diag2 = new Line2D.Double(upperRight, lowerLeft);
g2.draw(diag1); g2.draw(diag2);
} //=== paintCompenent
} //=== Panel
//====================== end of DrawPrimitive file =============================
// File: DrawTest2.java
/* 1. In DrawPanel class
a. create a static drawRectangle method whose 3 parameters are
a Graphics2D object, a Point2D object representing the upper-left corner,
and a Point2D object representing the lower-right corner
b. Test your implementation
*/
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class DrawTest2 {
public static void main(String[] args) {
DrawFrame frame = new DrawFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
} //=== main
} //=== class DrawTest2
class DrawFrame extends JFrame {
public static final int DEFAULT_WIDTH = 800;
public static final int DEFAULT_HEIGHT = 600;
public DrawFrame() {
setTitle("DrawTest2 Frame");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
DrawPanel panel = new DrawPanel();
Container contentPane = getContentPane();
contentPane.add(panel);
}
} //=== class DrawFrame
class DrawPanel extends JPanel {
public static void lineDraw(Graphics2D g, Point2D p, Point2D q) {
Line2D line = new Line2D.Double(p, q);
g.draw(line);
}
public static void pointDraw(Graphics2D g, Point2D p) {
Line2D line = new Line2D.Double(p, p);
g.draw(line);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
final int h = DrawFrame.DEFAULT_WIDTH/2; // use static final variables from DrawFrame class
final int k = DrawFrame.DEFAULT_HEIGHT/2;
final int r = 256;
final int r2 = r*r; // compute r^2 once, not over a 1000 times!!
g2.setPaint(Color.BLACK);
pointDraw(g2, new Point2D.Double(h, k));
g2.setPaint(Color.RED);
for (int x = h - r; x <= h + r; x++) {
double d = Math.sqrt(r2 - (x - h) * (x - h)); // compute (r^2 - (x - h)^2)^(1/2) once, not twice
Point2D p = new Point2D.Double(x, k + d);
pointDraw(g2, p);
p = new Point2D.Double(x, k - d);
pointDraw(g2, p);
}
g2.setPaint(Color.BLUE);
for (int y = k - r; y <= k + r; y++) {
double d = Math.sqrt(r2 - (y - k) * (y - k));
Point2D q = new Point2D.Double(h + d, y);
pointDraw(g2, q);
q = new Point2D.Double(h - d, y);
pointDraw(g2, q);
}
} //=== paintComponent
} //=== DrawPanel
//======================= end of DrawTest2 file ===========================
// revised paintComponent graphs concentric circles while moving (h, k)
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
int h = DrawFrame.DEFAULT_WIDTH/2;
int k = DrawFrame.DEFAULT_HEIGHT/2;
g2.setPaint(Color.BLACK);
pointDraw(g2, new Point2D.Double(h, k));
int rFirst = 300;
for (int r = rFirst; r > 0; r-=10) {
final int r2 = r*r;
g2.setPaint(Color.RED);
for (int x = h - r; x <= h + r; x++) {
double d = Math.sqrt(r2 - (x - h) * (x - h));
Point2D p = new Point2D.Double(x, k + d);
pointDraw(g2, p);
p = new Point2D.Double(x, k - d);
pointDraw(g2, p);
}
g2.setPaint(Color.BLUE);
for (int y = k - r; y <= k + r; y++) {
double d = Math.sqrt(r2 - (y - k) * (y - k));
Point2D q = new Point2D.Double(h + d, y);
pointDraw(g2, q);
q = new Point2D.Float(h - (float)d, y);
pointDraw(g2, q);
} //== for y
h += 5; k += 5;
}// == for rFirst
} //=== paintComponent
//=========================================================================================
// People1.java
// INSTRUCTIONS:
// 1. Copy this to People1.java file in your Objects or object directory
// 2. Create Student class:
// a. Implement getDescription and getID methods first, since classes won't compile until you override abstract methods
// b. getDesription should return class name followed by name, sex, grade, and GPA (see correct output shown below)
// 3. Create Employee class
// a. Implement getDescription and getID methods first, since classes won't compile until you override abstract methods
// b. getDesription should return class name followed by name, sex, and salary (see correct output shown below)
// 4. Run Program and check output against correct output shown below.
/* THIS IS THE OUTPUT YOU SHOULD GET:
--------------------------------------
0 Employee: name = Robert Cyrus, sex = female, salary = 41000.0, ID = 436071201
1 Student: name = Beverly Felix, sex = female, grade = sophomore, GPA = 2.2, ID = 437221015
2 Employee: name = Leslie Wolfgang, sex = female, salary = 40000.0, ID = 395096238
3 Student: name = Morris Albert, sex = female, grade = sophomore, GPA = 3.9, ID = 577804378
4 Employee: name = Patrice William, sex = female, salary = 43000.0, ID = 94905851
5 Student: name = Josephine Brooke, sex = male, grade = junior, GPA = 3.5, ID = 512334234
6 Employee: name = Juanita Othello, sex = male, salary = 44000.0, ID = 173255720
7 Student: name = Hoover Iago, sex = female, grade = senior, GPA = 2.0, ID = 899744531
*/
import java.util.*;
public class People1 {
static final String TAB = "\t";
public static void main(String[] args) {
MyTerminal.cls();
Person[] A = buildArray();
System.out.println(TAB + TAB + "Traversing an array of abstract Person object variables\n\n");
for (int k = 0; k < A.length; k++) {
System.out.println(k + TAB + A[k].getDescription() + ", ID = " + A[k].getID()) ;
}
} //=== main
static Person[] buildArray() {
String[] A = { "Robert", "Beverly", "Leslie", "Morris", "Patrice", "Josephine", "Juanita", "Hoover"};
String[] B = { "Iago", "Othello", "Brooke", "William", "Albert", "Wolfgang", "Felix", "Cyrus"};
Person[] P = new Person[A.length];
Random rGen = new Random(29L);
for (int k = 0; k < A.length; k++) {
String name = A[k] + " " + B[A.length-1-k];
if ( k % 2 == 0 ) {
//=== public Employee(String n, int Y, char s, double salary, String ssn)
P[k] = new Employee(name, 1965 + rGen.nextInt(21), (rGen.nextInt(2) == 1 ? 'M' : 'F'), 1000*rGen.nextInt(10) + 40000.0,
String.valueOf(rGen.nextInt(1000000000)));
}
else {
//=== public Student(String n, int Y, char s, String OS, double gpa, int gl)
P[k] = new Student(name, 1985 + rGen.nextInt(4), (rGen.nextInt(2) == 1 ? 'M' : 'F'), String.valueOf(rGen.nextInt(1000000000)),
2.0 + rGen.nextInt(20)/10.0, 1 + rGen.nextInt(4));
}
}// == for
return P;
} // === buildArray
} // ========================== end of People1 file =================================
// People2.java
// INSTRUCTIONS:
// 1. Copy this to People2.java file in your Objects or object directory
// 2. Using the Employee and Student classes you implemented recently
// A. Find the object or specified info
// 1. Minimum (lexicographic/dictionary-order) name and print description
// 2. The number of males and females
// B. Complete employeeInfo method started and specified below. WILL need to use instanceof operator
// EXAMPLE: if ( A[k] instanceof Employee ) { ...}
//
/* THIS IS THE INITIAL OUTPUT YOU SHOULD GET:
-----------------------------------------------
0 Employee: name = Shirley Sammie, sex = male, salary = 50000.0, ID = 52279084
1 Student: name = Beverly Piatte, sex = male, grade = sophomore, GPA = 2.2, ID = 273795851
2 Employee: name = Leslie Cyrus, sex = male, salary = 120000.0, ID = 675430954
3 Student: name = Morris Felix, sex = male, grade = sophomore, GPA = 3.9, ID = 257204047
4 Employee: name = Patrice Wolfgang, sex = male, salary = 50000.0, ID = 521076362
5 Student: name = Josephine Bertie, sex = female, grade = sophomore, GPA = 3.6, ID = 512334234
6 Employee: name = Juanita Fox, sex = male, salary = 100000.0, ID = 900054284
7 Student: name = Hoover Brooke, sex = female, grade = junior, GPA = 3.9, ID = 899744531
8 Employee: name = Agrippa Othello, sex = female, salary = 110000.0, ID = 473090230
9 Student: name = Denys Iago, sex = female, grade = sophomore, GPA = 2.2, ID = 145141436
10 Employee: name = Iago Denys, sex = female, salary = 130000.0, ID = 450720382
11 Student: name = Othello Agrippa, sex = male, grade = senior, GPA = 2.2, ID = 769056510
12 Employee: name = Brooke Hoover, sex = female, salary = 130000.0, ID = 727561657
13 Student: name = Fox Juanita, sex = male, grade = junior, GPA = 2.5, ID = 94931453
14 Employee: name = Bertie Josephine, sex = male, salary = 120000.0, ID = 443487378
15 Student: name = Wolfgang Patrice, sex = female, grade = sophomore, GPA = 2.4, ID = 362456537
16 Employee: name = Felix Morris, sex = female, salary = 80000.0, ID = 411758337
17 Student: name = Cyrus Leslie, sex = male, grade = freshman, GPA = 3.0, ID = 684958238
18 Employee: name = Piatte Beverly, sex = male, salary = 110000.0, ID = 230592553
19 Student: name = Sammie Shirley, sex = male, grade = sophomore, GPA = 3.2, ID = 926846884
*/
import java.util.*;
public class People2 {
static final String TAB = "\t";
static void employeeInfo(final Person[] A) {
// precond: A's Person object variables refer to 0 or more Employee objects
/* INSTRUCTIONS: 1. Create an array of Employee objects containing every Employee object referred to in A
2. Use array from instruction #1 to:
1. print out description and ID of every Employee
2. determine the average year of birth and salary of every Employee
3. Due Weds 12/10: determine the MEDIAN salary of the Employees:
HINT: modify Employee class by
a. inserting "implements Comparable" clause
b. implementing compareTo method based on salary
c. using java.util.Arrays.sort method
------------------------------------------------------------------------------------------ */
// YOUR CODE:
}//=== employeeInfo
public static void main(String[] args) {
MyTerminal.cls();
Person[] A = buildArray();
System.out.println(TAB + TAB + "Traversing an array of abstract Person object variables\n");
for (int k = 0; k < A.length; k++) {
System.out.println(k + TAB + A[k].getDescription() + ", ID = " + A[k].getID()) ;
}
MyTerminal.readString("\nPress <ENTER>...");
employeeInfo(A);
} //=== main
static Person[] buildArray() {
String[] A = { "Shirley", "Beverly", "Leslie", "Morris", "Patrice", "Josephine", "Juanita", "Hoover", "Agrippa", "Denys"};
String[] B = { "Iago", "Othello", "Brooke", "Fox", "Bertie", "Wolfgang", "Felix", "Cyrus", "Piatte", "Sammie"};
Person[] P = new Person[2*A.length];
Random rGen = new Random(29L);
final int LEN = A.length;
for (int k = 0; k < P.length; k++) {
String name = k < A.length ? A[k] + " " + B[A.length-1-k] : B[k % LEN] + " " + A[LEN-1-(k % LEN)];
char sex = rGen.nextInt(2) == 1 ? 'M' : 'F';
String ID = String.valueOf(rGen.nextInt(1000000000));
if ( k % 2 == 0 ) {
//=== public Employee(String n, int Y, char s, double salary, String ssn)
P[k] = new Employee(name, 1965 + rGen.nextInt(21), sex, 10000*rGen.nextInt(10) + 40000.0, ID);
}
else {
//=== public Student(String n, int Y, char s, String OS, double gpa, int gl)
P[k] = new Student(name, 1985 + rGen.nextInt(4), sex, ID,2.0 + rGen.nextInt(20)/10.0, 1 + rGen.nextInt(4));
}
}// == for
return P;
} // === buildArray
} // ========================== end of People2 file =================================
// People3.java
// INSTRUCTIONS:
// 1. Copy this to People3.java file in your Objects or object directory
// 2. Implement makeArray and findMinMax as specified below. (due Monday)
// 3. Implement compareTo (in Employee class at the end of THIS file) and findMedian (due Tues)
//
/* THIS IS THE INITIAL OUTPUT YOU SHOULD GET:
-----------------------------------------------
0 Shirley Sammie, class = Employee
1 Beverly Piatte, class = Student
2 Leslie Cyrus, class = Employee
3 Morris Felix, class = Student
4 Patrice Wolfgang, class = Employee
5 Josephine Bertie, class = Student
6 Juanita Fox, class = Employee
7 Hoover Brooke, class = Student
8 Agrippa Othello, class = Employee
9 Denys Iago, class = Student
10 Iago Denys, class = Employee
11 Othello Agrippa, class = Student
12 Brooke Hoover, class = Employee
13 Fox Juanita, class = Student
14 Bertie Josephine, class = Employee
15 Wolfgang Patrice, class = Student
16 Felix Morris, class = Employee
17 Cyrus Leslie, class = Student
18 Piatte Beverly, class = Employee
19 Sammie Shirley, class = Student
THIS IS THE OUTPUT YOU SHOULD GET FOR makeArray & findMinMax:
----------------------------------------------------------------
Array built by makeArray:
0 Beverly Piatte, sex = male, GPA = 2.727272727272727
1 Morris Felix, sex = female, GPA = 3.533333333333333
2 Josephine Bertie, sex = male, GPA = 2.727272727272727
3 Hoover Brooke, sex = female, GPA = 3.0
4 Denys Iago, sex = male, GPA = 3.9285714285714284
5 Othello Agrippa, sex = male, GPA = 2.927536231884058
6 Fox Juanita, sex = male, GPA = 2.727272727272727
7 Wolfgang Patrice, sex = male, GPA = 4.0
8 Cyrus Leslie, sex = male, GPA = 3.85
9 Sammie Shirley, sex = male, GPA = 3.933333333333333
Low male GPA: name = Beverly Piatte, GPA = 2.727272727272727
High female GPA: name = Morris Felix, GPA = 3.533333333333333
THIS IS THE OUTPUT YOU SHOULD GET FOR compareTo & getMedian:
----------------------------------------------------------------
median value = 3.2666666666666666
Array after sort in getMedian:
0 Beverly Piatte, GPA = 2.727272727272727
1 Josephine Bertie, GPA = 2.727272727272727
2 Fox Juanita, GPA = 2.727272727272727
3 Othello Agrippa, GPA = 2.927536231884058
4 Hoover Brooke, GPA = 3.0
5 Morris Felix, GPA = 3.533333333333333
6 Cyrus Leslie, GPA = 3.85
7 Denys Iago, GPA = 3.9285714285714284
8 Sammie Shirley, GPA = 3.933333333333333
9 Wolfgang Patrice, GPA = 4.0
-------------------------------------------------------------------
*/
import java.util.*;
public class People3 {
public static Student[] makeArray(final Person[] P) {
// precondition: P contains at least one object variable referring to a Student object
//postcondition: returns A. Every element in A refers to a Student object referred to in P. (No null references)
Student[] A = null;
return A;
}//=== makeArray
public static void findMinMax(final Student[] A) {
// precondition: A is the array created in makeArray method above. It contains at least one object variable
// referring to a female and a male Student object, getSex() returns upper case 'F' or 'M'
//postcondition: Prints name and GPA of: 1. female with highest GPA
// 2. male with lowest GPA
//System.out.println("Low male GPA: name = " + A[male].getName() + ", GPA = " + A[male].getGPA());
//System.out.println("High female GPA: name = " + A[female].getName() + ", GPA = " + A[female].getGPA());
} //=== minMax
public static double getMedian(final Student[] A) {
// precondition: A contains at least one object variable and no null references,
// java.util.Array.sort sorts array according to Student class's Comparable interface
//postcondition: returns median GPA score
return -77;
} //=== getMedian
static final String TAB = "\t";
public static void main(String[] args) {
MyTerminal.cls();
Person[] A = buildArray();
System.out.println(TAB + "Traversing an array of abstract Person object variables\n");
for (int k = 0; k < A.length; k++) {
System.out.println(k + TAB + A[k].getName() + ", class = " + A[k].getClass().getName()) ;
}
MyTerminal.readString("\nPress <ENTER>...");
//-----------------------------------------------------------
// Test makeArray and findMinMax: due Monday
//-----------------------------------------------------------
Student S[] = makeArray(A);
MyTerminal.cls();
System.out.println("\nArray built by makeArray:");
for (int k = 0; k < S.length; k++) {
String sex = S[k].getSex() == 'M' ? "male" : "female";
System.out.println(k + TAB + S[k].getName() + ", sex = " + sex + ", GPA = " + S[k].getGPA()) ;
}
System.out.println();
findMinMax(S);
MyTerminal.readString("\nPress <ENTER>...");
//----------------------------------------------------------
// Test compareTo and getMedian: due Tues
//-----------------------------------------------------------
MyTerminal.cls();
System.out.println();
System.out.println("median value = " + getMedian(S));
System.out.println("\nArray after sort in getMedian:");
for (int k = 0; k < S.length; k++) {
System.out.println(k + TAB + S[k].getName() + ", GPA = " + S[k].getGPA()) ;
}
} //=== main
static Person[] buildArray() {
String[] A = { "Shirley", "Beverly", "Leslie", "Morris", "Patrice", "Josephine", "Juanita", "Hoover", "Agrippa", "Denys"};
String[] B = { "Iago", "Othello", "Brooke", "Fox", "Bertie", "Wolfgang", "Felix", "Cyrus", "Piatte", "Sammie"};
Person[] P = new Person[2*A.length];
Random rGen = new Random(29L);
final int LEN = A.length;
for (int k = 0; k < P.length; k++) {
String name = k < A.length ? A[k] + " " + B[A.length-1-k] : B[k % LEN] + " " + A[LEN-1-(k % LEN)];
char sex = rGen.nextInt(2) == 1 ? 'M' : 'F';
String ID = String.valueOf(rGen.nextInt(1000000000));
if ( k % 2 == 0 ) {
//=== public Employee(String n, int Y, char s, double salary, String ssn)
P[k] = new Employee(name, 1965 + rGen.nextInt(21), sex, 10000*rGen.nextInt(10) + 40000.0, ID);
}
else {
//=== public Student(String n, int Y, char s, String OS, int points, int credits, int gLev)
int gLev = 1 + rGen.nextInt(4); int points = gLev*50 + rGen.nextInt(12); int credits = (int)(points/(2.0 + rGen.nextInt(20)/10.0));
P[k] = new Student(name, 1985 + rGen.nextInt(4), sex, ID, points, credits, gLev);
}
}// == for
return P;
} // === buildArray
} // ========================== end of People3 CLASS (file continues below)
class Student extends Person implements Comparable {
private String OSIS;
private int points;
private int credits;
private int gradeLevel; // (1,2,3,4) = (freshman,....senior)
final static String[] GRADE_LEVEL = { "unknown", "freshman", "sophomore", "junior", "senior"};
public Student(String n, int Y, char s, String OS, int points, int credits, int gLev) {
super(n, Y, s);
OSIS = OS; gradeLevel = gLev; this.points = points; this.credits = credits;
}
public Student() {
super();
OSIS = ""; gradeLevel = 0; points = credits = 0;
}
public String getID() { return OSIS; } // == overrides abstract method
public double getGPA() { return (double)points/credits;}
public int getGradeLevel() { return gradeLevel;}
public int compareTo(Object other) {
// precondition: Object refers to a Student object
//postcondition: implements Comparable interface on the basis of GPA
return 0;
} //=== compareTo
public String getDescription() { // == overrides abstract method
final String[] SEX = { "male", "female"};
int sexNum = 0;
if ( getSex() == 'F' || getSex() == 'f' ) sexNum = 1;
return getClass().getName() + ": name = " + getName() + ", sex = " + SEX[sexNum] + ", grade = " + GRADE_LEVEL[gradeLevel] + ", GPA = " + getGPA();
}
} // === Student
// // ========================== end of People3 file =================================
// Alist_1.java
// INSTRUCTIONS:
// 1. Copy this to Alist_1B.java file in your Objects or object directory
// 2. Implement makeArray and findMinMax as specified below. (due Weds)
// 3. Implement compareTo (in Employee class at the end of THIS file) and findMedian (due Thurs)
//
/* THIS IS THE INITIAL OUTPUT YOU SHOULD GET:
-----------------------------------------------
Traversing an array of abstract Person object variables
0 Brutus Bertie, class = Student, sex = male
1 Cyrus Denise, class = Employee, sex = male
2 Shirley Iago, class = Employee, sex = female
3 Felix Juanita, class = Employee, sex = male
4 Denise Cyrus, class = Employee, sex = female
5 Brooke Cato, class = Student, sex = female
6 Iago Shirley, class = Employee, sex = male
7 Pat Julius, class = Student, sex = female
8 Julius Pat, class = Student, sex = male
9 Juanita Felix, class = Employee, sex = female
10 Jason Leslie, class = Employee, sex = male
11 Josie Wolfgang, class = Employee, sex = female
12 August Patrice, class = Student, sex = male
13 Beverly Othello, class = Student, sex = female
14 Cato Brooke, class = Student, sex = male
15 Bertie Brutus, class = Student, sex = female
16 Othello Beverly, class = Student, sex = male
17 Wolfgang Josie, class = Employee, sex = male
18 Leslie Jason, class = Employee, sex = female
19 Patrice August, class = Student, sex = female
THIS IS THE OUTPUT YOU SHOULD GET FOR makeArray & findMinMax:
----------------------------------------------------------------
ArrayList built by makeArray:
0 Brutus Bertie, sex = male, GPA = 1.5
1 Brooke Cato, sex = female, GPA = 3.6
2 Pat Julius, sex = female, GPA = 2.5
3 Julius Pat, sex = male, GPA = 3.1
4 August Patrice, sex = male, GPA = 3.7
5 Beverly Othello, sex = female, GPA = 2.7
6 Cato Brooke, sex = male, GPA = 2.7888888888888888
7 Bertie Brutus, sex = female, GPA = 3.5
8 Othello Beverly, sex = male, GPA = 2.5
9 Patrice August, sex = female, GPA = 1.5
Low male GPA: name = Brutus Bertie, GPA = 1.5
High female GPA: name = Brooke Cato, GPA = 3.6
THIS IS THE OUTPUT YOU SHOULD GET FOR compareTo & getMedian:
----------------------------------------------------------------
median value = 2.7444444444444445
Array after sort in getMedian:
0 Brutus Bertie, GPA = 1.5, male
1 Patrice August, GPA = 1.5, female
2 Pat Julius, GPA = 2.5, female
3 Othello Beverly, GPA = 2.5, male
4 Beverly Othello, GPA = 2.7, female
5 Cato Brooke, GPA = 2.7888888888888888, male
6 Julius Pat, GPA = 3.1, male
7 Bertie Brutus, GPA = 3.5, female
8 Brooke Cato, GPA = 3.6, female
9 August Patrice, GPA = 3.7, male
-------------------------------------------------------------------
*/
import java.util.*;
public class Alist_1 {
public static ArrayList makeArray(final Person[] P) {
// precondition: P contains at least one object variable referring to a Student object
//postcondition: returns A. Every element in A refers to a Student object referred to in P. (No null references)
return null;
}//=== makeArray
public static void findMinMax(final ArrayList A) {
// precondition: A is the array created in makeArray method above. It contains at least one object variable
// referring to a female and a male Student object, getSex() returns upper case 'F' or 'M' DO NOT SORT
//postcondition: Prints name and GPA of: 1. female with highest GPA
// 2. male with lowest GPA
double maleGPA = -77.0, femaleGPA = -77.0;
String maleName = "XY" femaleName = "XX";
System.out.println("Low male GPA: name = " + maleName + ", GPA = " + maleGPA );
System.out.println("High female GPA: name = " + femaleName + ", GPA = " + femaleGPA );
} //=== minMax
public static void deleteAdd(ArrayList A, Person[] P) {
// precondition: A contains only Student object variables
// postcondition: 1. All Student objects with GPAs < 2.5 are deleted from A
// 2. All female Employee objects in P are used as the basis for adding new Students to A:
// In addition to the female Employee's name, YOB, and sex; use the SSN for the OSIS,
// set points & credits to 0 and gradeLevel to 1 (freshman)
/*--------------------------------------------------------------------------------
* median value = 2.5
Array after sort in getMedian:
0 Shirley Iago, GPA = 0.0, female
1 Denise Cyrus, GPA = 0.0, female
2 Juanita Felix, GPA = 0.0, female
3 Josie Wolfgang, GPA = 0.0, female
4 Leslie Jason, GPA = 0.0, female
5 Othello Beverly, GPA = 2.5, male
6 Pat Julius, GPA = 2.5, female
7 Beverly Othello, GPA = 2.7, female
8 Cato Brooke, GPA = 2.7888888888888888, male
9 Julius Pat, GPA = 3.1, male
10 Bertie Brutus, GPA = 3.5, female
11 Brooke Cato, GPA = 3.6, female
12 August Patrice, GPA = 3.7, male
* -----------------------------------------------------*/
}//=== deleteAdd
public static void sSort(ArrayList A) {
} //=== sSort
public static double getMedian(final ArrayList A) {
// precondition: A contains at least one object variable and no null references,
// java.util.Array.sort sorts array according to Student class's Comparable interface
//postcondition: returns median GPA score
//Collections.sort(A);
final int MID = A.size()/2;
sSort(A);
} //=== getMedian
static final String TAB = "\t";
public static void main(String[] args) {
MyTerminal.cls();
Person[] A = buildArray();
System.out.println(TAB + "Traversing an array of abstract Person object variables\n");
for (int k = 0; k < A.length; k++) {
System.out.println(k + TAB + A[k].getName() + ", class = " + A[k].getClass().getName() +
", sex = " + (A[k].getSex() == 'F' ? "female": "male")) ;
}
MyTerminal.readString("\nPress <ENTER>...");
//-----------------------------------------------------------
// Test makeArray and findMinMax: due Monday
//-----------------------------------------------------------
ArrayList S = makeArray(A);
MyTerminal.cls();
System.out.println("\nArrayList built by makeArray:");
for (int k = 0; k < S.size(); k++) {
Student student = (Student)S.get(k);
String sex = student.getSex() == 'M' ? "male" : "female";
System.out.println(k + TAB + student.getName() + ", sex = " + sex + ", GPA = " + student.getGPA()) ;
}
System.out.println();
findMinMax(S);
deleteAdd(S, A); // Add this to main later
MyTerminal.readString("\nPress <ENTER>...");
//----------------------------------------------------------
// Test compareTo and getMedian: due Tues
//-----------------------------------------------------------
MyTerminal.cls();
System.out.println();
System.out.println("median value = " + getMedian(S));
System.out.println("\nArray after sort in getMedian:");
for (int k = 0; k < S.size(); k++) {
Student s = (Student)S.get(k);
System.out.println(k + TAB + s.getName() + ", GPA = " + s.getGPA() + ", " + (s.getSex() == 'F' ? "female": "male"));
}
} //=== main
static Person[] buildArray() {
String[] F = { "Shirley", "Beverly", "Leslie", "Pat", "Patrice", "Josie", "Juanita", "Denise", "Bertie", "Brooke"};
String[] M = { "Iago", "Othello", "Jason", "Julius", "August", "Wolfgang", "Felix", "Cyrus", "Brutus", "Cato"};
Person[] P = new Person[2*F.length];
Random rGen = new Random(17L);
int len = F.length;
int pIdx = 0;
for (int k = 0; k < F.length; k++) {
int index = rGen.nextInt(len);
String femName = F[index] + " " + M[index], maleName = M[index] + " " + F[index];
String temp = F[len-1]; F[len-1] = F[index]; F[index] = temp;
temp = M[len-1]; M[len-1] = M[index]; M[index] = temp;
len--;
String femID = String.valueOf(rGen.nextInt(1000000000));
String maleID = String.valueOf(rGen.nextInt(1000000000));
if ( k % 2 == 0 ) {
//=== public Employee(String n, int Y, char s, double salary, String ssn)
P[pIdx++] = new Employee(femName, 1965 + rGen.nextInt(21), 'F', 10000*rGen.nextInt(10) + 40000.0, femID);
P[pIdx++] = new Employee(maleName, 1965 + rGen.nextInt(21), 'M', 10000*rGen.nextInt(10) + 40000.0, maleID);
}
else {
//=== public Student(String n, int Y, char s, String OS, int points, int credits, int gLevel)
int gLevel = 1 + rGen.nextInt(4);
int credits = 30 * gLevel, points = (int)(credits * (1 + (double)rGen.nextInt(30)/10));
P[pIdx++] = new Student(femName, 1986 + gLevel, 'F', femID, points, credits, gLevel);
gLevel = 1 + rGen.nextInt(4);
credits = 30 * gLevel; points = (int)(credits * (1 + (double)rGen.nextInt(30)/10));
P[pIdx++] = new Student(maleName, 1986 + gLevel, 'M', femID, points, credits, gLevel);
}
}// == for
int pLen = P.length;
for (int k = 0; k < P.length; k++) {
int index = rGen.nextInt(pLen);
Person tmp = P[index]; P[index] = P[pLen-1];
P[pLen-1] = tmp; pLen--;
}
return P;
} // === buildArray
} // ========================== end of Alist_1 CLASS (file continues below)
class Student extends Person implements Comparable {
private String OSIS;
private int points;
private int credits;
private int gradeLevel; // (1,2,3,4) = (freshman,....senior)
final static String[] GRADE_LEVEL = { "unknown", "freshman", "sophomore", "junior", "senior"};
public Student(String n, int Y, char s, String OS, int points, int credits, int gLev) {
super(n, Y, s);
OSIS = OS; gradeLevel = gLev; this.points = points; this.credits = credits;
}
public Student() {
super();
OSIS = ""; gradeLevel = 0; points = credits = 0;
}
public String getID() { return OSIS; } // == overrides abstract method
public double getGPA() {
if ( credits == 0 ) return 0.0;
else return (double)points/credits;
}
public int getGradeLevel() { return gradeLevel;}
public int compareTo(Object other) {
// precondition: Object refers to a Student object
//postcondition: implements Comparable interface on the basis of GPA
if ( !(other instanceof Student) ) return -77;
else {
Student std = (Student)other;
double diff = getGPA() - std.getGPA();
if ( Math.abs(diff) < 1e-8 ) return 0;
else if ( diff > 0 ) return 1;
else return -1;
}
} //=== compareTo
public String getDescription() { // == overrides abstract method
final String[] SEX = { "male", "female"};
int sexNum = 0;
if ( getSex() == 'F' || getSex() == 'f' ) sexNum = 1;
return getClass().getName() + ": name = " + getName() + ", sex = " + SEX[sexNum] + ", grade = " + GRADE_LEVEL[gradeLevel] + ", GPA = " + getGPA();
}
} // === Student
// // ========================== end of Alist_1 file =================================
public static void deleteAdd(ArrayList A, Person[] P) {
// precondition: A contains only Student object variables
// postcondition: 1. All Student objects with GPAs < 2.5 are deleted from A
// 2. All female Employee objects in P are used as the basis for adding new Students to A:
// In addition to the female Employee's name, YOB, and sex; use the SSN for the OSIS,
// set points & credits to 0 and gradeLevel to 1 (freshman)
/*
* median value = 2.754109589041096
* Array after sort in getMedian:
* 0 Leslie Cyrus, GPA = 0.0, female
* 1 Patrice Wolfgang, GPA = 0.0, female
* 2 Agrippa Othello, GPA = 0.0, female
* 3 Iago Denys, GPA = 0.0, female
* 4 Brooke Hoover, GPA = 0.0, female
* 5 Wolfgang Patrice, GPA = 2.7, male
* 6 Cyrus Leslie, GPA = 2.808219178082192, male
* 7 Othello Agrippa, GPA = 2.8421052631578947, male
* 8 Fox Juanita, GPA = 3.1044776119402986, female
* 9 Josephine Bertie, GPA = 3.440677966101695, male
* 10 Sammie Shirley, GPA = 3.5, female
* 11 Hoover Brooke, GPA = 3.709090909090909, female
---------------------------------------------------*/
}//=== end of deleteAdd
// Alist_2.java
// INSTRUCTIONS:
// 1. Copy this to Alist_2B.java file in your Objects or object directory
// 2. Implement maxGPA, deleteMaxGPA, appendList
//
/* THIS IS THE INITIAL OUTPUT YOU SHOULD GET:
-----------------------------------------------
ArrayList A (of Student):
0 Bertie Brutus, sex = female, GPA = 1.5
1 Jason Leslie, sex = male, GPA = 1.1
2 Patrice Augustus, sex = female, GPA = 1.4
3 Leslie Jason, sex = female, GPA = 3.6
4 Pat Julius, sex = female, GPA = 1.5
5 Wolfgang Josephine, sex = male, GPA = 3.0
6 Brutus Bertie, sex = male, GPA = 3.4
7 Cyrus Denise, sex = male, GPA = 1.6
8 Brooke Cato, sex = female, GPA = 3.3
9 Beverly Othello, sex = female, GPA = 3.6
10 Othello Beverly, sex = male, GPA = 3.8
11 Julius Pat, sex = male, GPA = 3.3
12 Cato Brooke, sex = male, GPA = 3.4
13 Shirley Iago, sex = female, GPA = 2.7
14 Iago Shirley, sex = male, GPA = 2.3
15 Augustus Patrice, sex = male, GPA = 3.2
16 Denise Cyrus, sex = female, GPA = 1.7
17 Juanita Felix, sex = female, GPA = 1.8
18 Felix Juanita, sex = male, GPA = 3.8
19 Josephine Wolfgang, sex = female, GPA = 3.4
*/
import java.util.*;
public class Alist_2 {
public static int maxGPA(ArrayList A) {
// precondition: Every object variable in A refers to a Student object. There is at least one Student object
//postcondition: returns the index of the Student object with the highest GPA
return -77;
} //=== maxGPA
public static void deleteMaxGPA(ArrayList A) {
// precondition: Every object variable in A refers to a Student object. There is at least one Student object.
//postcondition: the Student object with the highest GPA is deleted. Assume that the method maxGPA works as
// specified, regardless of what your wrote in question #1. You MUST use maxGPA in your answer.
} //=== deleteGPA
public static void appendList(ArrayList A, ArrayList B) {
// precondition: Every object variable in A and B refers to a Student object. There is at least one Student object in each.
//postcondition: 1. Every male Student object in A is deleted.
// 2. Every female Student object in B is added to A and then deleted from B
}//=== appendList
public static void sSort(ArrayList A) {
for (int k = 0; k < A.size() - 1; k++) {
int minPos = k;
for (int curr = minPos + 1; curr < A.size(); curr++) {
if ( ((Student)A.get(curr)).compareTo(A.get(minPos)) < 0 ) {
minPos = curr;
}
}
Object temp = A.get(k);
A.set(k, A.get(minPos));
A.set(minPos, temp);
}// for k
} //=== sSort
static final String TAB = "\t";
public static void main(String[] args) {
MyTerminal.cls();
ArrayList A = buildArray();
System.out.println(TAB + "ArrayList A (of Student):\n");
for (int k = 0; k < A.size(); k++) {
Student student = (Student)A.get(k);
String sex = student.getSex() == 'M' ? "male" : "female";
System.out.println(k + TAB + student.getName() + ", sex = " + sex + ", GPA = " + student.getGPA());
}
int maxPos = maxGPA(A);
Student s = (Student)A.get(maxPos);
System.out.println("\nStudent with highest GPA is: " + s.getName() + ", GPA = " + s.getGPA() + ", index = " + maxPos);
deleteMaxGPA(A);
System.out.println(TAB + "\nArrayList A (of Student) after deleteMaxGPA() :\n");
for (int k = 0; k < A.size(); k++) {
Student student = (Student)A.get(k);
String sex = student.getSex() == 'M' ? "male" : "female";
System.out.println(k + TAB + student.getName() + ", sex = " + sex + ", GPA = " + student.getGPA());
}
MyTerminal.readString("\nPress <ENTER>...");
MyTerminal.cls();
System.out.println("\nArrayLists A and B before appendList:\n");
System.out.println(TAB + TAB + "ArrayList A" + TAB + TAB + TAB + TAB + TAB + "ArrayList B");
//=== build ArrayList B
ArrayList B = new ArrayList();
final int MID = A.size()/2;
for (int k = MID; k < 2*MID; k++)
B.add(A.remove(MID));
for (int k = 0; k < A.size(); k++) {
Student student = (Student)A.get(k);
String sex = student.getSex() == 'M' ? "male" : "female";
System.out.print(k + TAB + student.getName() + ", sex = " + sex + ", GPA = " + student.getGPA());
if ( k < B.size() ) {
student = (Student)B.get(k);
sex = student.getSex() == 'M' ? "male" : "female";
System.out.print(TAB + TAB + student.getName() + ", sex = " + sex + ", GPA = " + student.getGPA());
}//=== if
System.out.println();
} //=== for
appendList(A, B);
System.out.println("\nArrayLists A and B after appendList:\n");
System.out.println(TAB + TAB + "ArrayList A" + TAB + TAB + TAB + TAB + TAB + "ArrayList B");
for (int k = 0; k < A.size(); k++) {
Student student = (Student)A.get(k);
String sex = student.getSex() == 'M' ? "male" : "female";
System.out.print(k + TAB + student.getName() + ", sex = " + sex + ", GPA = " + student.getGPA());
if ( k < B.size() ) {
student = (Student)B.get(k);
sex = student.getSex() == 'M' ? "male" : "female";
System.out.print(TAB + TAB + student.getName() + ", sex = " + sex + ", GPA = " + student.getGPA());
}//=== if
System.out.println();
} //=== for
} //=== main
static ArrayList buildArray() {
String[] F = { "Shirley", "Beverly", "Leslie", "Pat", "Patrice", "Josie", "Juanita", "Denise", "Bertie", "Brooke"};
String[] M = { "Iago", "Othello", "Jason", "Julius", "August", "Wolfgang", "Felix", "Cyrus", "Brutus", "Cato"};
int len = F.length;
Random rGen = new Random(19L);
ArrayList A = new ArrayList();
for (int k = 0; k < F.length; k++) {
//======= female
int index = rGen.nextInt(len); String name = F[index] + " " + M[index];
String ID = String.valueOf(rGen.nextInt(1000000000)); int gLevel = rGen.nextInt(4) + 1;
int credits = 30 * gLevel, points = (int)(credits * (1 + (double)rGen.nextInt(30)/10));
// public Student(String n, int Y, char s, String OS, int points, int credits, int gLev)
int pos = A.size() > 0 ? rGen.nextInt(A.size()) : 0;
A.add(pos, new Student(name, 1988 + gLevel, 'F', ID, points, credits, gLevel) );
//======= male
name = M[index] + " " + F[index];
ID = String.valueOf(rGen.nextInt(1000000000)); gLevel = rGen.nextInt(4) + 1;
credits = 30 * gLevel; points = (int)(credits * (1 + (double)rGen.nextInt(30)/10));
// public Student(String n, int Y, char s, String OS, int points, int credits, int gLev)
A.add(rGen.nextInt(A.size()) , new Student(name, 1988 + gLevel, 'M', ID, points, credits, gLevel) );
String temp = F[index]; F[index] = F[len-1]; F[len-1] = temp;
temp = M[index]; M[index] = M[len-1]; M[len-1] = temp;
len--;
}// == for
return A;
} // === buildArray
} // ========================== end of Alist_2 CLASS (file continues below)
class Student extends Person implements Comparable {
private String OSIS;
private int points;
private int credits;
private int gradeLevel; // (1,2,3,4) = (freshman,....senior)
final static String[] GRADE_LEVEL = { "unknown", "freshman", "sophomore", "junior", "senior"};
public Student(String n, int Y, char s, String OS, int points, int credits, int gLev) {
super(n, Y, s);
OSIS = OS; gradeLevel = gLev; this.points = points; this.credits = credits;
}
public Student() {
super();
OSIS = ""; gradeLevel = 0; points = credits = 0;
}
public String getID() { return OSIS; } // == overrides abstract method
public double getGPA() {
if ( credits == 0 ) return 0.0;
else return (double)points/credits;
}
public int getGradeLevel() { return gradeLevel;}
public int compareTo(Object other) {
// precondition: Object refers to a Student object
//postcondition: implements Comparable interface on the basis of GPA
if ( !(other instanceof Student) ) return -77;
else {
Student std = (Student)other;
double diff = getGPA() - std.getGPA();
if ( Math.abs(diff) < 1e-8 ) return 0;
else if ( diff > 0 ) return 1;
else return -1;
}
} //=== compareTo
public String getDescription() { // == overrides abstract method
final String[] SEX = { "male", "female"};
int sexNum = 0;
if ( getSex() == 'F' || getSex() == 'f' ) sexNum = 1;
return getClass().getName() + ": name = " + getName() + ", sex = " + SEX[sexNum] + ", grade = " + GRADE_LEVEL[gradeLevel] + ", GPA = " + getGPA();
}
} // === Student
// // ========================== end of Alist_2 file =================================
// Array2D.java
// INSTRUCTIONS:
// 1. Implement maxVal, maxRowSum, and maxColSum as specified below
// 2. Implement rotateRight and rotateMatrix as specified
/*=====================================================================
CORRECT OUTPUT:
2-Dimensional array exercises
M equals:
11 22 33 44 55
21 31 41 51 61
10 20 30 84 50
1 2 3 4 5
The maximum value = 84
The largest row sum = 205
The largest column sum = 183
Press <RETURN>...
Before rotateRight:
A equals: 15 25 35 45 55
After rotateRight:
A equals: 55 15 25 35 45
--------------------------------------------------------
Before rotateMatrix:
M equals:
11 22 33 44 55
21 31 41 51 61
10 20 30 84 50
1 2 3 4 5
After rotateMatrix:
M equals:
5 11 22 33 44
55 21 31 41 51
61 10 20 30 84
50 1 2 3 4
----------------------------------------------------------*/
public class Array2D {
static int maxVal(final int[][] M) {
//postcond: returns value of largest element in M
return -77;
} //=== maxVal
static int maxRowSum(final int[][] M) {
// precond: all row sums are positive
//postcond: returns largest sum of all the row sums
return -77;
} //===maxRowSum
static int maxColSum(final int[][] M) {
// precond: all column sums are positive
//postcond: returns largest sum of all the column sums
return -77;
} //===maxColSum
static void rotateRight(int[] A) {
// Every element is shifted to right except last element, which is
// assigned to first position. See EXAMPLE below
// precond: A = { -1, -2, -3, -4, -5}
//postcond: A = { -5, -1, -2, -3, -4}
} //===rotateRight
static void rotateMatrix(int[][] M) {
// In answering this question, use rotateRight
// PRECONDITION POSTCONDITION
// M = -1, -2, -3 M = -9, -1, -2
// -4, -5, -6 -3, -4, -5
// -7, -8, -9 -6, -7, -8
//---------------------------------------------
final int COLS = M[0].length;
final int ROWS = M.length;
} //===rotateMatrix
static final String TAB = "\t";
public static void main(String args[]) {
MyTerminal.cls();
System.out.println("2-Dimensional array exercises\n");
int[][] M = make2D();
drive3(M);
drive2(M);
} //=== main
static void drive3(final int[][] m) {
print(m);
System.out.println("\nThe maximum value = " + maxVal(m));
System.out.println("The largest row sum = " + maxRowSum(m));
System.out.println("The largest column sum = " + maxColSum(m));
}//=== drive3
static void drive2(int[][] m) {
int A[] = { 15, 25, 35, 45, 55};
MyTerminal.readString("\nPress <RETURN>...");
System.out.println();
System.out.println("Before rotateRight:");
print(A);
rotateRight(A);
System.out.println("After rotateRight:");
print(A);
System.out.println("\n--------------------------------------------------------\n");
System.out.println("Before rotateMatrix:");
print(m);
rotateMatrix(m);
System.out.println("After rotateMatrix:");
print(m);
}//=== drive2
static int[][] make2D() {
return new int[][] { {11, 22, 33, 44, 55},
{21, 31, 41, 51, 61},
{10, 20, 30, 84, 50},
{1, 2, 3, 4, 5}};
}//=== make2D
static void print(final int[][] m) {
System.out.println(TAB + "M equals:");
for (int r = 0; r < m.length; r++) {
System.out.print(TAB);
for (int c = 0; c < m[0].length; c++) {
System.out.print(m[r][c] + TAB);
}
System.out.println();
}
} //===print
static void print(final int[] A) {
System.out.print(TAB + "A equals: ");
for (int c = 0; c < A.length; c++) {
System.out.print(A[c] + TAB);
}
System.out.println();
} //===print
} //================================================== end of Array2D file
Quiz 7 solutions
public static int maxGPA(ArrayList A) {
// precondition: Every object variable in A refers to a Student object. There is at least one Student object
//postcondition: returns the index of the Student object with the highest GPA
// VERSION 1: down cast to a local variable // VERSION 2: downcast on the fly
//-----------------------------------------------------------------------------------------------------
int maxPos = 0; // int maxPos = 0;
for (int k = 0; k < A.size(); k++) { // for (int k = 0; k < A.size(); k++) {
Student current = (Student) A.get(k); // if ( ((Student)A.get(k)).compareTo(A.get(maxPos)) > 0 )
if ( current.compareTo(A.get(maxPos)) > 0 ) // maxPos = k;
maxPos = k; // } //=== for
} // return maxPos
return maxPos;
} //=== maxGPA
public static void deleteMaxGPA(ArrayList A) {
// precondition: Every object variable in A refers to a Student object. There is at least one Student object.
//postcondition: the Student object with the highest GPA is deleted. Assume that the method maxGPA works as
// specified, regardless of what your wrote in question #1. You MUST use maxGPA in your answer.
A.remove(maxGPA(A));
} //=== deleteGPA
public static void appendList(ArrayList A, ArrayList B) {
// precondition: Every object variable in A and B refers to a Student object. There is at least one Student object in each.
//postcondition: 1. Every male Student object in A is deleted.
// 2. Every female Student object in B is added to A and then deleted from B
for (int k = 0; k < A.size(); ) {
if ( ((Student)A.get(k)).getSex() == 'M' ) //LOGIC: can't increment k after deletion!!!
A.remove(k);
else
k++;
} //=== for
for (; B.size() > 0 ; ) {
if ( ((Student)B.get(0)).getSex() == 'M' ) B.remove(0);
else A.add(B.remove(0));
}//== for
}//=== appendList