1. Java . Create CONSTRUCTOR FUNCTIONS (Creating data according to your abstraction)
int[] createMoney(int dollars, int cents); // Given the
number of dollars and cents, construct a Money abstraction. If
given >99 cents, convert it to dollars. Abstraction is a process
of hiding the implementation details from the user.
int[] copyMoney(int[] money); // Given a money, create a separate
copy of it.
if needed, use Functions, Conditionals, Loops, and or Arrays
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
// Test.java
public class Test {
// method to create an array containing 2 elements, first element holds the
// amount in dollars, second element holds the remaining cents
static int[] createMoney(int dollars, int cents) {
// if cents >99, finding extra dollars by dividing cents by 100
if (cents > 99) {
int extraDollars = cents / 100;
// removing extra dollars from cents
cents = cents % 100;
// adding extraDollars to dollars
dollars += extraDollars;
}
// creating a 2 element array with dollars being first element and cents
// being second, returning this array
int money[] = { dollars, cents };
return money;
}
// returns the copy of the given money array
static int[] copyMoney(int[] money) {
// creating an array of same capacity
int copy[] = new int[money.length];
// copying all elements from money array to copy array
for (int i = 0; i < money.length; i++) {
copy[i] = money[i];
}
return copy;
}
public static void main(String[] args) {
// testing createMoney and copyMoney methods
int money[] = createMoney(15, 125);
int copy[] = copyMoney(money);
System.out.println(money[0] + " dollars and " + money[1] + " cents");
System.out.println("Copy: " + copy[0] + " dollars and " + copy[1]
+ " cents");
}
}
/*OUTPUT*/
16 dollars and 25 cents
Copy: 16 dollars and 25 cents
Get Answers For Free
Most questions answered within 1 hours.