Modify the program below:
public class LenghtArray {
public static void main(String[] args) {
int[] ages = {16, 19, 30, 60, 21, 25, 2, 13};
// Print all elements
for (int count = 0; count < ages.length; count++) {
System.out.print(ages[count] + " ");
}
// Sum of all ages
System.out.println(" ");
int total = 0;
for (int count = 0; count < ages.length; count++) {
total = total + ages[count];
}
System.out.print("Total :" + total + " ");
}
}
Here down is my expected output:
Input length of an array: 4
age[0]: 65
age[1]: 10
age[2]: 60
age[3]: 18
Display all elements in an array: 65, 10, 60, 18
Total: 153
So far here's what I have, I don't know what's wrong with it. My professor said you just need to add 2 string of lines. I keep on adding more
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int[] ages = {0};
System.out.println("Input length of an array:");
int number = inp.nextInt();
for (int count = 0; count < number; count++) {
System.out.println("age[" + count + "]: ");
ages[count] = inp.nextInt();
}
// Print all elements
for (int count = 0; count < ages.length; count++) {
System.out.print(ages[count] + " ");
}
// Sum of all ages
System.out.println(" ");
int total = 0;
for (int count = 0; count < ages.length; count++) {
total = total + ages[count];
}
System.out.print("Total :" + total + " ");
}
int [] ages= {};is an array with length 0. You can't access any of its indices (and you should be getting anIndexOutOfBoundsException)array2class.