this is my code
import java.util.*;
public class testq
{
public static void main (String [] args)
{
int max = 0;
int sum = 0;
int count = 0;
int age, maximum;
double average;
Scanner sc = new Scanner(System.in);
age = sc.nextInt();
while (age != 0)
{
System.out.println("enter age");
age = sc.nextInt();
if (age < 0 && age > 120)
{
System.out.println("enter numbers between 1 to 120");
age = sc.nextInt();
}
else
{
count ++;
sum = sum + age;
maximum = getMax(max, age);
average = getAve(sum, count);
}
}
System.out.println(" max is" + max + "average is" + average);
}
public static int getMax (int max, int age)
{
if (max < age)
{
max = age;
}
return max;
}
public static double getAve (int sum, int count)
{
double average;
average = (double)sum / (double)count;
return average;
}
}
this is what i have i need to input values between 1 to 120 until 0 is input and calculate max and average of those values if i compile this code i get error message
"average might not have been initialised"
i was thinking maybe somethings wrong with the count so the method for calculating average might not have executed properly. i cant think of anything else than that at the moment could i get help what went wrong please?
edit*
my code looks like this now
import java.util.*;
public class testq
{
public static void main (String [] args)
{
int max = 0;
int sum = 0;
int count = 0;
int age, maximum;
double average;
Scanner sc = new Scanner(System.in);
System.out.println("enter age");
age = sc.nextInt();
while (age != 0)
{
System.out.println("enter age");
age = sc.nextInt();
if (age < 0 || age > 120)
{
System.out.println("enter numbers between 1 to 120");
age = sc.nextInt();
}
else
{
count ++;
sum = sum + age;
}
}
maximum = getMax(max, age);
average = getAve(count, sum);
System.out.println(" maximum is " + max + "average is " + average);
}
but the problem now is max is always 0 and average is always close to 0. also when i input numbers it takes in the negative values as well for example
enter age
-10
enter age
-10
enter numbers between 1 to 120
-10
enter age
-10
enter numbers between 1 to 120
0
i wanted to out put "enter numbers between 1 to 120 everytime invalid number is input
ive tried changing the while condition to (age != 0 && age >=1 && age <=120) but didnt work