1. 程式人生 > 其它 >Java輸出陣列對應的索引值

Java輸出陣列對應的索引值

技術標籤:陣列java陣列

在一個數組中,找出其中是否存在x,若存在,輸出對應的索引值(索引是從0開始計數的)
public class Bubble2 {

	public static void main(String[] args) {
		int[] arr = new int[] { 45, 78, -6, 0, 456, -11 };
		int x = 456;
		boolean isExist = true;
		for (int i = 0; i < arr.length; i++) {
			if (x == arr[i]) {
				System.out.print
("索引值為:" + i); isExist = false; break; } } if (isExist == true) { System.out.println("抱歉,您輸入的數不存在該陣列中!"); } } }

輸出結果:
在這裡插入圖片描述
若輸入的數不存在,輸出結果為:
在這裡插入圖片描述