有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在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;
    }
    }

共 (2) 个答案

  1. # 1 楼答案

    从returnIndex方法引发异常,并在main方法中捕获相同的异常

    下面是示例。我已经使用了现有的NoTouchElementException

      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");
    }
    

    注:仅用于演示目的。理想情况下,您不应该捕获运行时异常

  2. # 2 楼答案

    要抛出异常,只需使用throw关键字:

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

    为了优雅地结束,需要使用try { ... } catch(Exception e){ ..}语句捕获main方法中的异常