2015-08-27 6 views
-1

У меня есть java.lang.ArrayIndexOutOfBoundsException, и я думаю, что это происходит потому, что когда nums.length дает мне нуль (потому что в параметр ничего не вставлено) атрибут, который я дал переменной (- ----. length -1 ------) сделает -1, когда он даст мне нуль.ArrayIndexOutOfBoundsException, когда .length равно нулю

Как я могу заставить это не делать этого, зная, что если я оставлю его .length без -1, будет исключение вне границ на другой стороне массива?

public boolean sameFirstLast(int[] nums) { 
     int lengthOfArray = nums.length - 1; 
     int thisIsHowLong = nums.length; 

     if (nums[0] == nums[lengthOfArray ] && thisIsHowLong > 0){ 
     return true; 
     } 


    return false; 
} 

//always remember to return false in the end becuse if the top dosnt run then 
//there will be no boolean returned and the method is not void so it has to return a //boolean 

//ALWAYS REMEMBER TO SET nums.length - 1 
//the .length method always starts from 1 and threfore will give you an extra space //that it will check for but we wont have anything in that space and then the compiler //will go to that space and will fond nothing to test with and gove an ERROR out of //bounds exeption because it is looking out of the array. 
+0

Пожалуйста, используйте 'nums.length() - 1' внутри индекса массива, например. 'nums [nums.length() -1]' –

+0

изменить порядок ваших обоих условий. – SacJn

ответ

1

Необходимо обменивать условия.

if (thisIsHowLong > 0 && nums[0] == nums[lengthOfArray ]){ // This will prevent the exception. 
2

Ваше состояние должно выглядеть
if(thisIsHowLong > 0 && nums[0] == nums[lengthOfArray ])

Теперь, если ваше первое условие ложно, второй никогда не будет проверяться. И вы хотите того же.