2014-09-03 17 views
-5
int arr[] = new int[10]; 
int size=0; 
while(???) 
{ 
    i++; 
} 

System.out.println(size); // Should print 10 

如何在不使用arr.length或其他庫函數的情況下遍歷數組?如何在不使用庫函數/變量的情況下查找數組的大小/長度

+3

*「沒有使用arr.lenth ...」* - 爲什麼? – MadProgrammer 2014-09-03 01:08:26

+5

這就像是問「如何停車而不使用休息時間」 - 一堵牆很好,但你不會喜歡結果...... – MadProgrammer 2014-09-03 01:14:31

+0

*或其他庫功能*。你確定這是用於Java嗎? – 2014-09-03 01:20:44

回答

2
 
int arr[] = new int[100]; 

int sum = 0; 
int i = 0; 
while (true) { 
    try { 
    sum += arr[i]; 
    } catch (ArrayIndexOutOfBoundsException e) { 
    break; 
    } 
    i++; 
} 

System.out.println("Array is of size " + i); 

我假設數組是int,但想法是一樣的。

+0

所以...基本上我們使用ArrayOutOfBoundsException來中斷並計算。有沒有任何方法可以在不使用此異常的情況下計算大小 – Navchetan 2014-09-03 01:10:37

+0

這不是對你的挖掘,而是給其他讀這個的人的一個說明,不知道更好,[爲什麼不使用異常作爲正常的控制流?](http://stackoverflow.com/questions/729379/why -not-use-exceptions-as-regular-flow-of-control),[不要使用例外進行流量控制](http://c2.com/cgi/wiki?DontUseExceptionsForFlowControl),[作爲控制流的異常被認爲是嚴重的反模式?如果是這樣,爲什麼?](http://programmers.stackexchange.com/questions/189222/are-exceptions-as-control-flow-considered-a-serious-antipattern-if-so-why)...和我可以繼續...... – MadProgrammer 2014-09-03 01:11:15

+0

是的..很不好,但工程..總和+ = arr [i]是否有原因,否則編譯器可能會刪除「arr [i]」語句,看到它不用於任何事情。 – 2014-09-03 01:11:42

0

引擎蓋下,你會得到一個。長度(除非你使用一個奇怪的編譯器),但因爲這個問題有點兒奇怪...

int[] array = new int[100]; 
int size = 0; 

for(int i : array){ 
    ++size; 
} 

System.out.println("Size: " + size); 

我還是不明白點

相關問題