共計 769 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以使用 Arrays
類中的 binarySearch()
方法或者自己寫一個循環來判斷一個元素是否在數組中。
使用 binarySearch()
方法需要先對數組進行排序,然后調用該方法,它會返回要查找的元素在數組中的索引。如果返回的索引大于等于 0,則表示該元素在數組中存在。否則,表示該元素不在數組中。
示例代碼如下所示:
import java.util.Arrays;
public class Main {public static void main(String[] args) {int[] arr = {1, 2, 3, 4, 5};
int target = 3;
// 先對數組進行排序
Arrays.sort(arr);
// 使用 binarySearch()方法判斷元素是否存在
int index = Arrays.binarySearch(arr, target);
if (index >= 0){System.out.println(target + " 在數組中存在 ");
} else {System.out.println(target + " 不在數組中存在 ");
}
}
}
另外,也可以自己寫一個循環來判斷元素是否在數組中。代碼如下所示:
public class Main {public static void main(String[] args) {int[] arr = {1, 2, 3, 4, 5};
int target = 3;
boolean exists = false;
// 使用循環判斷元素是否存在
for (int i : arr) {if (i == target) {exists = true;
break;
}
}
if (exists) {System.out.println(target + " 在數組中存在 ");
} else {System.out.println(target + " 不在數組中存在 ");
}
}
}
丸趣 TV 網 – 提供最優質的資源集合!
正文完