[英]For loop logic runs but doesn't make sense
VisitProcedure.length 等於 7
所以出於某種原因,這種方法可以按照我想要的方式工作。 但這個邏輯對我來說毫無意義。 我有一個7的數組,我希望用戶輸入索引0-6 的某些部分,它將顯示該索引處的值。 如果他們輸入的數字超出范圍,則會引發異常。 但這就是我閱讀 if 語句邏輯的方式
如果索引小於 0 或索引大於 6 執行此操作 (p = VisitProcedure[index].getProcedure(); //顯示索引
但它恰恰相反。 當我選擇0-6 時,它會在該索引處顯示數組的值。 當我做其他任何事情時,它都沒有索引。 同樣,當我嘗試不同的邏輯時
如果索引大於等於 0 且小於 7 執行此操作
我仍然遇到錯誤。 但基本上一切正常,對我來說為什么沒有意義。
public Procedure GetByIndex(int index)throws ArrayIndexOutOfBoundsException {
Procedure p;
if (index < 0 || index > 1 - VisitProcedure.length) { //switching 1 - to - 1 still doesnt work
p = VisitProcedure[index].getProcedure();
return p;
}
else{
ArrayIndexOutOfBoundsException ar;
ar = new ArrayIndexOutOfBoundsException();
throw ar;
//throw new ArrayIndexOutOfBoundsException();
}
}
您當前的代碼是錯誤的,但由於以下原因它仍然有效:
如果您傳遞有效索引(0 到 6 之間),則index > 1 - VisitProcedure.length
為true
(因為1 - VisitProcedure.length
為負),因此 if 條件為true
並且您返回VisitProcedure[index].getProcedure()
.
如果傳遞無效index > 6
或index < 0
,條件仍然為true
,並且訪問數組的無效索引會拋出ArrayIndexOutOfBoundsException
(即它仍然會拋出,但不是由else
子句拋出)。
換句話說,您的條件始終為true
,因此您的代碼等效於:
public Procedure GetByIndex(int index)throws ArrayIndexOutOfBoundsException {
return VisitProcedure[index].getProcedure();
}
If(index>0 && index<=VisitProcedure.length-1){
//if index is greater than 0 and less than or equal to index 6
p = VisitProcedure[index].getProcedure();
return p;
}else{
ArrayIndexOutOfBoundsException ar;
ar = new ArrayIndexOutOfBoundsException();
throw ar;
//throw new ArrayIndexOutOfBoundsException();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.