Reputation: 11
I need to write a program which accepts non-negative double type of numbers as income amounts one by one unti l a negative number is entered , and the negative number ends the program. When the program is completed by entering a negative number , it prints out the minimum, average, and maximum for the set of entered incomes (excluding the last negative number be cause it only indicates the end of user input).
package incomeapp;
import java.util.Scanner;
/**
*
* @author Kenneth
*/
public class IncomeApp {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an income (any negative number to quit: ");
double sum = 0;
int count = 0;
double i = sc.nextDouble();
while (i > 0){
double nextDouble;
nextDouble = sc.nextDouble();
if (i < 0){
break;
}
}
}
}
Upvotes: 1
Views: 1073
Reputation: 272
Try this:
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter an income (any negative number to quit: ");
double sum = 0;
double max = 0;
double min = Double.MAX_VALUE;
int count = 0;
double nextDouble;
while (sc.hasNext()) {
nextDouble = sc.nextDouble();
max = Math.max(max, nextDouble);
if (nextDouble < 0){
break;
}else {
min = Math.min(nextDouble, min);
sum += nextDouble;
count++;
}
}
System.out.println("Average: " + sum/count);
System.out.println("Min: " + min);
System.out.println("Max: " + max);
}
}
Upvotes: 0
Reputation: 11113
There's a few issues with your code here:
Now, this seems very much like a programming assignment to me so I'm not going to post the complete code for you. Here's what you should do to fix your code though:
Pick one way of terminating the loop. Here's two ideas on how to do it:
double i = sc.nextDouble();
while (i > 0) {
// Do something with i
i = sc.nextDouble();
}
or
while (true) {
double i = sc.nextDouble();
if (i <= 0) {
break;
}
// Do something with i
}
Upvotes: 1