我對Java相當陌生,正在嘗試撰寫一個方法來回傳陣列中最長的數字的起始索引。(如果陣列是 {2,3,5,5,5,2,2} 則應回傳“2”,因為它是相同數字的最長字串的開始)。
在我的代碼中,我有一個 while 回圈,只要陣列中的下一個數字等于當前值,它就應該繼續運行。(將運行直到出現新號碼)。
while((i < values.length) && (values[i] == values[i 1]))
{
currentRun ;
i ;
}
如果在陣列末尾發生運行,這可能會導致索引越界錯誤。{3,7...5,5,5} 因為它將繼續回圈并最終嘗試檢查不存在的索引的值。為了防止這種情況發生,我嘗試添加條件并確保索引值必須小于陣列的長度,但是當我使用 java 可視化工具時,無論第一部分如何,它總是繼續運行 for 回圈的條件。
誰能解釋一下為什么會發生這種情況以及如何解決?
(下面的完整程式代碼)
public class NumberCube
{
public static int getLongestRun(int[] values)
{
int longestIndex = -1;
int currentIndex = 0;
int longestRun = 1;
int currentRun = 0;
for(int i = 0; i < values.length - 1; i )
{
if(values[i] == values[i 1])
{
currentIndex = i;
while((i < values.length) && (values[i] == values[i 1]))
{
currentRun ;
i ;
}
}
if (currentRun > longestRun)
{
longestRun = currentRun;
longestIndex = currentIndex;
}
currentRun = 1;
}//end for loop
return longestIndex;
}//end method
public static void main(String[] args){
int[] values = {3, 5, 6, 6, 3, 6, 4, 4, 4, 2, 6, 4, 1, 1, 1, 1};
int longestRunIdx = getLongestRun(values);
if(longestRunIdx != 12){
System.out.println("Your code does not return the correct index.");
if(longestRunIdx == 2 || longestRunIdx == 6)
System.out.println("It is returning the start index of a run, but that run is not the longest.");
System.out.println("Remember that your code must return the start index of the longest run of tosses.");
} else {
System.out.println("Looks like your code works well!");
}
}
}
uj5u.com熱心網友回復:
它會檢查,查詢不會阻止無效訪問,因為陣列是從零開始的。因此,例如 if array.length == 1, thenarray[0]是有效的,但array[1]不是。
對于i == 0,您同時訪問兩者,因此 的索引無效i 1。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/407757.html
標籤:
