2013-12-20 64 views
1

循環問題這是代碼,我現在所擁有的人簡單與陣列

for (int i = 0; i <= listOfPeople.length; i++){ 
    String name = scnr.nextLine(); 
    System.out.println("Person " + (i + 1) + ": "); 
    listOfPeople[i] = name; 
} 

列表是一個字符串與用戶發送值的長度正確申報清單。正在發生的錯誤是,當我運行該程序,我得到這個:

Person 1: 

Jordan 

Person 2: 

Jordan 

Person 3: 

Jordan 

Person 4: 

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 
    at RGG.main(RGG.java:20) 

我不太知道什麼是錯的,但我已經試過在去除= for循環聲明,然後我得到這樣的輸出:

Person 1: 

Jordan 

Person 2: 

Jordan 

Person 3: 

第三次提示後,代碼繼續,我無法輸入任何內容。 有誰知道可能會發生什麼?提前致謝!

+0

正如我在質詢時說,「我曾嘗試在for循環聲明中去掉=」,它仍然失敗,請參閱上面的問題 –

回答

2

刪除=的表達式i <= listOfPeople.length;。它導致你訪問不存在的數組元素。

for (int i = 0; i < listOfPeople.length; i++){ 
     String name = scnr.nextLine(); 
     System.out.println("Person " + (i) + ": "); 
     listOfPeople[i] = name; 
} 

全部實施例:

public class PersonArrayTest { 

    public static void main(String[] args) { 
     String[] listOfPeople = new String[5]; 
     assign(listOfPeople); 
     System.out.println(Arrays.toString(listOfPeople)); 
    } 

    public static void assign(String[] listOfPeople) { 

     Scanner scnr = new Scanner(System.in); 
     for (int i = 0; i < listOfPeople.length; i++) { 
      String name = scnr.nextLine(); 
      System.out.println("Person " + (i) + ": "); 
      listOfPeople[i] = name; 
     } 
    } 
} 
2

利用這種線

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

您正在推進一個超過數組,長度爲3,其具有有效索引0-2的端部。 3是一個無效索引。

當您刪除=,你會得到修正版本:

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

2迭代,這是數組的結尾,你跑出陣列結束之前之後停止。

1

改變這個<=標誌在for循環

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

我讓一個受過教育的猜測,您正在使用Scanner#nextInt以獲取數組的長度的輸入。沿此線的東西:

String[] listOfPeople = new String[scnr.nextInt()]; 

我已經獲取了這一點,因爲你的循環代碼如下所示:

 
take input for i == 0 
print prompt #1 
take input for i == 1 
print prompt #2 
take input for i == 2 
print prompt #3 

但是你的輸出顯示這一點:

 
print prompt #1 
take input for i == 1 
print prompt #2 
take input for i == 2 
print prompt #3 

那麼究竟是什麼必須發生的是:

 
silently advance past whatever scnr is still retaining for i == 0 
print prompt #1 
take input for i == 1 
print prompt #2 
take input for i == 2 
print prompt #3 

nextInt孤兒一個新行字符。 (除了nextLine之外,還有其他任何對next_的調用。)這就是爲什麼你的第一個輸入被跳過。在循環的第一次迭代中調用scnr.nextLine只會使掃描器超過最後一行。

改變循環到這一點:

// skip the last new line 
scnr.nextLine(); 

// < not <= 
for (int i = 0; i < listOfPeople.length; i++) { 

    // prompt before input 
    System.out.println("Person " + (i + 1) + ": "); 

    // you don't need that extra String 
    listOfPeople[i] = scnr.nextLine(); 
}