2015-09-30 82 views
2

我目前得到一個數組越界異常在執行線name.firstName = this.firstNames[rand.nextInt(NUM_NAMES)];通常情況下我沒有發現這些異常,但是我一直停留在這一個一段時間以來的來源問題。任何幫助表示讚賞,類和堆棧跟蹤粘貼如下:Java數組索引越界異常修復

public class NameGenerator { 
    private static final int NUM_NAMES = 200; 
    private static final File NAMES_FILE = new File("resources/info.dat"); 

    /** a random number generator */ 
    private Random rand; 

    /** the array of first names */ 
    private String[] firstNames; 
    /** the array of last names */ 
    private String[] lastNames; 

    /** 
    * Default Constructor 
    */ 
    public NameGen() { 
     super(); 
     this.rand = new Random(); 

     try { 
      readFile(); 
     } catch (IOException exp) { 
      this.first = new String[] { "foo" }; 
      this.last = new String[] { "bar" }; 
     } 
    } 

    /** 
    * Read the names from the file 
    */ 
    private void readNFiles() throws IOException { 
     List<String> tempFirst = new ArrayList<String>(); 
     List<String> tempLast = new ArrayList<String>(); 

     Scanner scnr = new Scanner(NAMES_FILE); 

     while (scnr.hasNext()) { 
      tempFirst.add(scnr.next()); 
      tempLast.add(scnr.next()); 
     } 

     scnr.close(); 

     int size = tempFirst.size(); 

     this.first = new String[size]; 
     tempFirst.toArray(this.firstNames); 

     this.last = new String[size]; 
     tempLast.toArray(this.last); 
    } 

    /** 
    * @return a generated name 
    */ 
    public FullName generateName() { 
     FullName name = new FullName(); 
     name.first = this.firstNames[rand.nextInt()]; 

     name.last = this.lastNames[rand.nextInt()]; 
     return name; 
    } 

    /** 
    * Class describing a full name 
    */ 
    public static final class FullName { 
     /** the first name */ 
     public String firstName; 
     /** the last name */ 
     public String lastName; 
    } 
} 
+0

也許'rand.nextInt(NUM_NAMES - 1)'? – MadProgrammer

+1

沒有解決問題:( – GregH

+1

我沒有看到任何地方,你叫'generateName'。考慮提供[可運行示例](https://stackoverflow.com/help/mcve),這說明您的問題。這不是一個代碼轉儲,但你在做什麼哪你凸顯遇到的問題的例子。這將導致更少的混亂和更好的反應 – MadProgrammer

回答

1

基於...

try { 

    readNamesFiles(); 

} catch (IOException exp) { 

    this.firstNames = new String[] { "John" }; 
    this.lastNames = new String[] { "Doe" }; 

} 

沒有保證您的陣列將包含NUM_NAMES元素(你應該記錄在異常至少)。

所以使用類似name.firstName = this.firstNames[rand.nextInt(NUM_NAMES)];有potional導致一些嚴重的問題,因爲你已經發現。

相反,你應該與現實的假設,而不是工作,用更多的東西一樣......

name.firstName = this.firstNames[rand.nextInt(this.firstNames.length)]; 
1

這裏是你的問題的代碼摘要:

List<String> tempFirstNames = new ArrayList<String>(NUM_NAMES); 
int size = tempFirstNames.size(); 

this.firstNames = new String[size]; 
FullName name = new FullName(); 
name.firstName = this.firstNames[rand.nextInt(NUM_NAMES)]; 

您正在使用rand.nextInt(NUM_NAMES)作爲數組索引分爲firstNames。這將生成一個介於0和NUM_NAMES之間的數字。問題是無法保證數組firstNames的尺寸爲NUM_NAMES。正如@AngryProgrammer指出的那樣,您可以使用它來代替:

name.firstName = this.firstNames[rand.nextInt(firstNames.length)];