該程序應該詢問有多少動物在野外留下5次。然後它應該使用第二種方法輸出相同的信息。但我無法弄清楚這一點。每次我根據以前的問題改變任何東西的時候,我只是添加了一些錯誤。爲什麼我的簡單數組無法正常工作?
import java.util.Scanner;
class animals {
public static void main(String[] args) {
int[] q1 = question();
output(q1);
System.exit(0);
} // 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};
number++;
}//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
所以這個編譯好了,然後當我每次循環後增加在終端5個號碼,我得到
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)
除了事實,即時得到的文本,提供的這些monodo蛟龍號是最終我輸入不是第
請注意'System.exit(0)'在主要方法的末尾沒有用處。 – martijnn2008
我會從編譯的代碼開始,當你添加每一行時,確保它在編譯之前添加更多的'int [number] record = {};'永遠不會編譯在這種情況下,添加更多的代碼將會是增加混亂。 –
注意:數組開始數組0不是1.每次調用'record = new int [] {howMany};'時,替換先前的值。只保留最後一個值。 –