In: Computer Science
2. Create ACCESSOR FUNCTIONS in JAVA
a) String moneyToString(int[] money); // Returns a nice looking
string. Ex, "$6.25", "$0.21", "$4.01", "$2.00". MAKE SURE TO
CONSIDER ALL EXAMPLES!
b) *String moneyToText(int[] money); // Returns the Money as words.
Ex,{123,51} => "one hundred and twenty three dollars and fifty
one cents." YOU MAY ASSUME money <$1000.
context:
this is what I have so far
package com.company; import java.util.*; public class Main { public static void main(String[]args) { int money[] = createMoney(12, 34); int copy[] = copyMoney(money); } static int[] createMoney(int dollars, int cents) { if (cents>99) { int extraDollars=cents/100; cents=cents%100; dollars+=extraDollars; } int money[] = { dollars, cents }; return money; } static int[] copyMoney (int[]money) { int copy[]=new int[money.length]; for (int i=0; i<money.length; i++) { copy[i]=money[i]; } return copy; } }
2.
a)
CODE
public static String moneyToString(int[] money) {
String result = "$";
if (money.length == 1) {
result += money[0];
} else if (money.length == 2) {
result += money[0];
if (money[1] != 0) {
result += "." + money[1];
}
} else {
result = "";
}
return result;
}
B)
CODE
public static String convert(final int n) {
String[] units = { "", "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve",
"Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen",
"Eighteen", "Nineteen" };
String[] tens = {
"", // 0
"", // 1
"Twenty", // 2
"Thirty", // 3
"Forty", // 4
"Fifty", // 5
"Sixty", // 6
"Seventy", // 7
"Eighty", // 8
"Ninety" // 9
};
if (n < 20) {
return units[n];
}
if (n < 100) {
return tens[n / 10] + ((n % 10 != 0) ? " " : "") + units[n % 10];
}
return units[n / 100] + " Hundred" + ((n % 100 != 0) ? " " : "") + convert(n % 100);
}
public static String moneyToText(int[] money) {
String result = "";
if (money.length == 2) {
result += convert(money[0]) + " dollars and " + convert(money[1]) + " cents.";
} else if (money.length == 1) {
result += convert(money[0]) + " dollars.";
}
return result;
}