-4

Can you help with this issue.I have to implement task that have function divides given amount of money among a given number of people and returns a list of values how much each person should receive.The numbers in the output can be with up to 2 decimal places and The difference between 2 amounts from the returned list must not be greater than 0.01, or one.

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Insert amount");
    double amount = scanner.nextDouble();
    System.out.println("Insert people");
    int numberOfPeople = scanner.nextInt();

    List<Double> values = printList(amount, numberOfPeople);
    printresults(values);


}

private static void printresults(List<Double> values) {
         for (Double amount : values) {

        System.out.printf("%.2f ",amount);
    }
}


private static List<Double> printList(double amount, int numberOfPeople) {
    double result = 0;
    List<Double> moneys = new ArrayList<>();
    for (int i = 1; i <= numberOfPeople; i++) {
        result = (amount / numberOfPeople);

        moneys.add(result);
    }

    return moneys;
}



}
  • Don't try to represent money using `double` or `float`. Instead, use `long` or `BigDecimal`. If you use `long`, the value will be in pennies, mills, or some other fraction of the base unit. Example: `12345` will represent $123.45. for United States dollars. – James Jun 04 '22 at 03:05
  • `long amtToDistribute; long amtEach = amtToDistribute / numberOfPeople; int leftOver = (int) ( amtToDistribute % numberOfPeople) ;` and the first `leftOver` people get a penny more than the rest. – James Jun 04 '22 at 03:21
  • See https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency – James Jun 04 '22 at 03:22

0 Answers0