In: Computer Science
In Java,
Programmers do all money calculations using cents, represented as an integer, like 635 cents. A useful method in such an approach might convert cents into separate dollar and cents values. Write a method centsToDollarsCents whose parameter is given cents and returns an array of integers containing numDollars and numCents, respectively. If the first argument is 635, the array would contain [6, 35].
I understand how to solve for numDollars and numCents but I am having trouble returning the array. If anyone could help that would be appreciated.
Please find the below code
import java.util.Arrays;
import java.util.Scanner;
public class Sample {
public static int[] centsToDollarsCents(int numberInCents)
{
int[] result = new int[2];
int numDollars = 0, numCents = 0;
// 100 cents = 1 dollar
if(numberInCents < 100) {
numCents = numberInCents;
result[0] = numDollars;
result[1] = numCents;
}
else {
numDollars = numberInCents / 100; // To get the dollar value
numCents = numberInCents % 100; // To get the cent value
result[0] = numDollars;
result[1] = numCents;
}
return result;
}
public static void main(String[] args)
{
System.out.println("Enter the number in cents:");
Scanner in = new Scanner(System.in);
int number = in.nextInt();
int[] res = centsToDollarsCents(number);
System.out.println("Result: "+ Arrays.toString(res));
}
}
Please find the attached image as an output