# Help with a loop-like problem

• 10-13-2009, 11:14 PM
Jnoobs
Help with a loop-like problem
Hi all, first post here.

I had a question about a program i was thinking of writing but am having trouble with finishing.

Quote:

Input contains several money amounts. Each represents a donation. The ned is denoted by a negative amount. The program will print each amount on a separate line, with a dollar sign. At the end it will print a blank line, total donations, and the average. Note that the amounts as well as the average are printed to two decimal places, rounded.
The output for an input such as 24.95 64.50 77 -89.90 will be

\$ 24.95
\$ 64.50
\$ 77.00

Total from 3 donations = \$ 166.45
Average = \$ 55.48
the thing is i get stuck here

Code:

import java.util.*;

public class Prog5
{
public static void main(String args[])
{
double donations, total, average;

Scanner sea = new Scanner(System.in);

do
donations = sea.nextDouble();
while(donations >= 0);

System.out.printf("%.2d", donations);

}
}

i know i havent started writing the code for the total and average, but i first need to know how i get this stupid loop to work with the total and average.

• 10-14-2009, 01:15 AM
Jnoobs
nevermind, i think i got it

Code:

import java.util.*;
import java.text.DecimalFormat;

public class Prog5
{
public static void main(String args[])
{
double donations, average, total;
int i;
String input;
char repeat;

DecimalFormat formatter = new DecimalFormat("#,##0.00");
Scanner sea = new Scanner(System.in);

i = 0;
total = 0;

do
{
System.out.print("\nDonation: ");
donations = sea.nextDouble();

if(donations < 0)
donations = 0;

sea.nextLine();

i++;
total += donations;
average = total / i;

System.out.println("\nAnother donation? ");
System.out.print("Enter Y for yes or N for no: ");
input = sea.nextLine();
repeat = input.charAt(0);
}
while(repeat == 'Y' || repeat == 'y');

System.out.println("\nTotal from " + i + " donations = \$ " + total);
System.out.println("Average = \$ " + formatter.format(average));

}
}