這個任務,我將如何添加一個例外打印「元素的數組找不到」如何解決Java的
分配:
創建與搜索的整數數組的一個方法的Java程序指定的整數值(請參閱下面的啓動方法標題的幫助)。如果數組包含指定的整數,則該方法應該返回數組中的索引。如果沒有,該方法應拋出一個異常,聲明「在數組中找不到元素」並優雅地結束。用你製作的數組和「針」的用戶輸入測試主要的方法。
我的代碼:
package chapter12;
import java.util.Scanner;
public class Assignment1 {
public static void main(String[] args) {
int[] haystack = { 1,2,3,10,11,12,320,420,520,799,899,999 };
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number in the array: ");
int needle = sc.nextInt();
int index = returnIndex(haystack, needle);
if(index!=-1)
System.out.println("Element found at index : " + index);
}
public static int returnIndex(int[] haystack, int needle) {
for (int n = 0; n < haystack.length; n++) {
if (haystack[n] == needle)
return n;
}
System.out.println("Element not found in array");
return -1;
}
}
'拋出新的異常(「在數組中找不到元素」);' – yeedle