actually you don't need to declare a and b outside of loop since you are not accessing them outside of the loop .and when you count average then u need to count all ages so put a variable out side and add ages to it .and there is no need to store ages in a String
.use int array for ages ..
double agecount = 0;
and in java int/int ==int
.if you divide a int by a int
you get a int
value but for average int is not good you could use double
instead.because of this put a variable double agecount
.and you have to cast one int
to double
double avarageAge = agecount / names.length;
and don't forget java array indexes are zero based .you are leaving first element empty [default value].
for (int i =1; i < names.length; i++)
change to
for (int i = 0; i < names.length; i++)
example code
public static void users() {
String[] names = new String[5];
int[] ages = new int[5];
for (int i = 0; i < names.length; i++) {
String a = JOptionPane.showInputDialog(null, "What's your name, user " + (i+1) + "?");
int b = Integer.parseInt(JOptionPane.showInputDialog(null, "What is your age, " + a + "?"));
names[i] = a;
ages[i] = b;
}
double agecount = 0;
for (int i = 0; i < names.length; i++) {
agecount += ages[i];
System.out.println("User " + (i+1) + ": " + names[i] + " " + ages[i] + " years old");
}
double avarageAge = agecount /names.length;
System.out.println("The avarage age for this quiz is " + avarageAge);
}
output of for sample inputs >>
User 1: u1 22 years old
User 2: u2 10 years old
User 3: u3 15 years old
User 4: u4 54 years old
User 5: u5 12 years old
The avarage age for this quiz is 22.6