2013-07-29 30 views
1

我是初學java和我寫了這個代碼:我的java程序將無法正常運行。

class Friends { 
    public static void main(String[] args) { 
     String[] facebookFriends = { "John", "Joe", "Jack", "Lucy", "Bob", "Bill", "Sam", "Will" }; 
     int x = 0; 
     while (x <= 8) { 
      System.out.println("Frind number " + (x + 1) + " is " + facebookFriends[x]); 
      x++; 
     } 
     System.out.println(""); 

     if (facebookFriends.length < 5) { 
      System.out.println("Where are all you're friends?"); 
     } 
     else if (facebookFriends.length == 5) { 
      System.out.println("You have a few friends..."); 
     } 
     else { 
      System.out.println("You are very sociable!"); 
     } 
    }  
} 

當我運行它正確讀取的名字,但它不顯示任何文本,如節目「你有幾個朋友......「或」你非常善於交際!「另外,當我運行它時,在第三個和第四個名稱之間顯示「線程中的異常」main「java.lang.ArrayIndexOutOfBoundsException:8」。我不知道我的代碼有什麼問題,但如果有人能告訴我這個問題,我將不勝感激。謝謝。而不是

+0

數組從0到length-1的 你必須做',而(X <8)'因爲你的長度爲8 – Loki

+0

你沒有得到第三之間的誤差第四。在最後一個之後你會得到錯誤。只是在第四個打印在標準輸出流中之前打印錯誤流。在每個'System.out.println(...)'之後,你可以做一個'System.out.flush()'(刷新意味着現在打印,而不是當緩衝區已滿時)看到這種效果。 –

回答

1

x <= 8應該是x < 8

facebookFriends數組有8個元素(索引從07)。嘗試訪問超出此範圍的任何位置將導致ArrayIndexOutOfBoundsException異常。

+0

THANKYOU SOOOOOOOOOOOOO很多!我不敢相信我沒有看到! –

3

while (x <= 7)while (x <= 8)

陣列在Java中,從0開始,而不是1

如果你看一下例外:

「異常線程 「main」 的java.lang .ArrayIndexOutOfBoundsException: 8「

它告訴你發生了什麼事NG。

+0

通常對於數組,我認爲使用'i hexafraction

+0

對,即使我更喜歡那樣,不知道爲什麼我用這個:) – rocketboy

5
while (x <= 8) { 
    System.out.println("Frind number " + (x + 1) + " is " + facebookFriends[x]); 
    x++; 
} 

試圖最終讀取facebookFriends[8]。這是不可能的,因爲它從0到7

用途:

while (x < facebookFriends.length) { 

代替。

+4

更好的是'while(x

0

正如其他人已經指出的那樣,它應該是x <= 7,x < 8或更好的x < facebookFriends.length,因爲Java數組基於零(0)。

編寫代碼的另一種方法是:

class Friends 
{ 
    public static void main(String[] args) 
    { 
     String[] facebookFriends = { "John", "Joe", "Jack", "Lucy", "Bob", "Bill", "Sam", "Will" }; 

     int length = facebookFriends.length; 
     int num = 1; 
     for (String friend: facebookFriends) 
      System.out.println("Friend number " + (num++) + " is " + friend); 

     System.out.println(""); 

     if (length < 5) 
      System.out.println("Where are all your friends?"); 
     else if (length == 5) 
      System.out.println("You have a few friends..."); 
     else 
      System.out.println("You are very sociable!"); 
    }  
} 
0

如果u真的想讓它一般用途 而(X < = facebookFriends.length) 這將確保它工作得很好,即使數量朋友在陣列增加或減少