2016-11-26 81 views
0

該程序應該詢問有多少動物在野外留下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蛟龍號是最終我輸入不是第

+3

請注意'System.exit(0)'在主要方法的末尾沒有用處。 – martijnn2008

+0

我會從編譯的代碼開始,當你添加每一行時,確保它在編譯之前添加更多的'int [number] record = {};'永遠不會編譯在這種情況下,添加更多的代碼將會是增加混亂。 –

+1

注意:數組開始數組0不是1.每次調用'record = new int [] {howMany};'時,替換先前的值。只保留最後一個值。 –

回答

3

這是沒有意義的

int[number] record = {}; 

最喜歡你的意思是

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

,取而代之的

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

你需要

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

,而不是它創建1個值的數組以下[0]

record = new int[] {howMany}; 

,當您嘗試訪問[1]

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

你需要

record[i] = howMany; 

當你寫的每行代碼在你的IDE(或編輯器),你應該看看是否編譯,將產生以下和如果它不添加更多的行不太可能有所幫助。我建議你儘可能頻繁地進行編譯和測試,這樣你就知道錯誤的來源以及發生錯誤的位置,你可以在調試器中單步執行代碼,看看程序爲什麼沒有達到你期望的效果。

0

這是你所需要的:

int number = 0; int[] record = new int[5];

,哪些是你需要進行另一個修改:從最後一行

int howMany = scanner.nextInt(); record[number] = howMany;

刪除評論。

現在你的程序應該可以正常工作。

瞭解一些關於數組的基本知識。

相關問題