2017-06-28 31 views
1

這個任務,我將如何添加一個例外打印「元素的數組找不到」如何解決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; 
    } 
    } 
+3

'拋出新的異常(「在數組中找不到元素」);' – yeedle

回答

5

拋出異常,你只需使用throw關鍵字:

throw new Exception("Element not found in array");

要結束擺好,你需要捕捉異常在main方法使用一個try { ... } catch(Exception e){ ..}聲明。

1

從returnIndex方法拋出一個異常,並在main方法中捕獲相同的異常。

下面是示例。我已經使用了現有的NoSuchElementException。

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(); 
    try { 
     int index = returnIndex(haystack, needle); 
     System.out.println("Element found at index : " + index); 
    }catch (NoSuchElementException ex){ 
     System.out.println(ex.getMessage()); 

    } 
} 

public static int returnIndex(int[] haystack, int needle) throws NoSuchElementException { 
    for (int n = 0; n < haystack.length; n++) { 
     if (haystack[n] == needle) 
      return n; 
    } 
    throw new NoSuchElementException("Element not found in array"); 
} 

注意:它僅用於演示目的。理想情況下,您不應該捕獲運行時異常。