Write a program that asks the user to type in ages. They will type a negative age when they finish entering the ages. The program will print out the average of all of the ages and the oldest age entered. It should end with a newline.
Sample output #1
Type a negative for age to exit Enter your age: 21 Enter your age: 22 Enter your age: 21 Enter your age: -8 The average age is: 21.33 The oldest person is: 22 years old
Sample output #2
Type a negative for age to exit Enter your age: -10 No ages were entered
This is what I have so far:
import java.util.Scanner;
public class Main
{
public static void main(String [] args) {
Scanner kb = new Scanner(System.in);
int age;
int max;
int count;
int avg;
System.out.println("Type a negative for age to exit");
System.out.print("Enter your age: ");
age = kb.nextInt();
avg = 0;
count = 0;
avg = age;
max = age;
while(age > 0) {
System.out.print("Enter your age: ");
age = kb.nextInt();
if(max < age) {
max = age;
}
if(age < 0) {
avg = avg + age;
count = count + 1;
}
if(count <= 0){
System.out.println("No ages were entered");
}
else {
System.out.printf("The average age is: %.2f\n", (1.0 * avg /
count));
System.out.println("The oldest person is: " + max + " years
old");
}
}
}
}
getting these errors:
1.
Input
-5
Your output
Type a negative for age to exit Enter your age:
Expected output
Type a negative for age to exit Enter your age: No ages were entered
2.
Input
95 -5
Your output
Type a negative for age to exit Enter your age: Enter your age: The average age is: 90.00 The oldest person is: 95 years old
Expected output
Type a negative for age to exit Enter your age: Enter your age: The average age is: 95.00 The oldest person is: 95 years old
// NOTE: I have fixed the code
import java.util.Scanner;
public class Main
{
public static void main(String [] args) {
Scanner kb = new Scanner(System.in);
int age;
int max;
int count;
float avg;
int sum=0;
System.out.println("Type a negative for age to exit");
System.out.print("Enter your age: ");
age = kb.nextInt();
avg = 0;
count = 0;
avg = age;
max = age;
while(age > 0) {
if(max < age) {
max = age;
}
sum=sum+age;
count=count+1;
System.out.print("Enter your age: ");
age = kb.nextInt();
}
avg=(float)sum/count;
if(count == 0){
System.out.println("No ages were entered");
}
else {
System.out.printf("The average age is: %.2f\n", avg);
System.out.println("The oldest person is: " + max + " years
old");
}
}
}
Get Answers For Free
Most questions answered within 1 hours.