John Smith John Smith - 1 year ago 79
Java Question

Why are my arrays not working?

This is a part of a program I'm making to learn the basics of java. The program should ask the user how many of a given animal are left in the wild 5 times, each time asking for a different animal through the use of arrays. It should then store each of the values provided by the user in another array(I'm not sure if this is actually possible but i've tried it, suggest an alternative if its not). And then i would use these values to output data. But I haven't got there yet as this code does not work. I'm sure its something obvious.

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;
for (int i = 1; i <= 5; i++) {
System.out.println(wild[number] + ":");
Scanner left = new Scanner(;
System.out.println("How many are left in the wild?");
String howMany = left.nextLine();
String[] record = {};
record[number] = howMany;

return number;
}// end method question

} // end class animals

Answer Source

you are not initialising your Array but only declaring it: Try like this:

String[] wild =new String[] { "Komodo Dragon", "Mantee", "Kakapo", "Florida Panther", "White Rhino" };

Read from here: How to initialize an array in Java?

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