Avi Lal Avi Lal - 1 year ago 65
Java Question

why do my simple arrays not work?

This program should ask how many of an animal are left in the wild 5 times. Then it should use a second method to output the same information. But i cant figure this out; every time i change anything based on previous questions here i just add to the number of errors.

import java.util.Scanner;

class animals {

public static void main(String[] args) {

int[] q1 = question();


} // exit main

public static int[] question() {
String[] wild = { "Komodo Dragon", "Mantee", "Kakapo", "Florida Panther", "White Rhino" };
int number = 0;
int[] record = {};
for (int i = 1; i <= 5; i++) {
System.out.println(wild[number] + ":");
Scanner scanner = new Scanner(System.in);
System.out.println("How many are left in the wild?");
int howMany = scanner.nextInt();
record = new int[] {howMany};

}//end for loop

return record;

}// end method question

public static void output(int[] q1){
System.out.println("There are " + q1[0] + " Komodo Dragons in the wild");
System.out.println("There are " + q1[1] + " Mantees in the wild");
System.out.println("There are " + q1[2] + " Kakapos in the wild");
System.out.println("There are " + q1[3] + " Florida Panthers in the wild");
System.out.println("There are " + q1[4] + " White Rhinos in the wild");
}//end method output

} // end class animals

So this compiles alright, then when i've added 5 numbers in terminal after each loop i get

There are 3 Komodo Dragons in the wild
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at animals.output(animals.java:39)
at animals.main(animals.java:13)

Other than the fact that im getting the text, the monodo dragon number being provided is the last number i input not the first

Answer Source

This doesn't make sense

int[number] record = {};

most like what you meant was

int[] record = new int[wild.length];

and instead of

for (int i = 1; i <= 5; i++) {

you need

for (int i = 0; i < wild.length; i++) {

instead of the following which creates an array of 1 value [0]

record = new int[] {howMany};

which will produce the following when you try to access [1]

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1

you need

record[i] = howMany;

As you write each line of code in your IDE (or your editor) you should see if that compiles and if it doesn't adding more lines is unlikely to help. I suggest you try to compile and test as often as possible so you know where the source of your errors are and when you get a bug, you can step through the code in your debugger to see why the program is not doing what you expect.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download