java - 异常处理修复

标签 java

我的代码多次打印“在数组中找不到元素”,以获取数组中的该数字,为什么以及如何解决这个问题。

我的作业:

使用一个方法创建一个 Java 程序,该方法在整数数组中搜索指定的整数值(请参阅下面有关启动方法头的帮助)。如果数组包含指定的整数,则该方法应返回其在数组中的索引。如果没有,该方法应该抛出一个异常,指出“在数组中找不到元素”并正常结束。使用您创建的数组和“针”的用户输入来测试 main 中的方法。

public static int returnIndex(int[ ] haystack, int Needle) {

到目前为止我的代码:

import java.util.Scanner;
public class Assignment1 {

 public static void main(String[] args) {
     int[] haystack = { 4,5,6,7,12,13,15,16,22,66,99,643 };        
     Scanner sc = new Scanner(System.in);
     System.out.println("Enter a number in the array: ");                
     int needle = sc.nextInt();
     returnIndex(haystack,needle);

   }
 public static int returnIndex(int[] haystack, int needle) {
        for (int n = 0; n < haystack.length; n++) {
            if (haystack[n] == needle) 
                return n;
            else 
                System.out.println("Element not found in array");
        }
        return -1;  
    }
 }

我的输出:

Enter a number in the array: 
7
Element not found in array
Element not found in array
Element not found in array

Enter a number in the array: 
15
Element not found in array
Element not found in array
Element not found in array
Element not found in array
Element not found in array
Element not found in array

最佳答案

您会多次获得相同的输出,因为您没有跳出循环。此外,如果仅当您迭代整个数组时,数组中不存在元素,因此请移动 System.out.println("Element在 for 循环之外的数组中找不到");。下面是完整的示例,请看一下。

用户在下面的代码中,如果在数组中找不到元素,我将中断循环。

public class SOTest {
    public static void main(String[] args) {
        int[] haystack = { 4, 5, 6, 7, 12, 13, 15, 16, 22, 66, 99, 643 };
        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) // print index only if element is in array.
        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;

    }
}

编辑:- 添加了可运行代码和示例输入和输出以验证程序的正确性。还添加了如果在数组中找到元素则打印索引的逻辑,-1 索引表示元素不在数组中。

数字的输入和输出:- 120,该数字不在数组中。

Enter a number in the array: 
120
Element not found in array

对于数组中的数字 5,输出将如下:-

Enter a number in the array: 
5
Element found at index : 1

关于java - 异常处理修复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44752634/

相关文章:

java - 基于注释的安全限制不适用于 Web 套接字触发的方法调用

java - Java中什么情况下需要同步数组?

java - JSON 字符串到集合 Java

java - 如何将 HashMap 保存到 Android 中的文件?

java - xxx(JNIEnv *env, jobject thisObj) 和 xxx(JNIEnv *env, jclass cls) 有什么区别?

java - 使用 Java 实现字符串数组 "is in"方法的有效方法

java - 在 Linux (CentOS 5.4) 中运行 jNotify 时出现问题

javascript - ScriptEngine JavaScript 不支持 Contains?

java - 向服务器发送 POST 请求

java - LibGDX:非投影世界坐标如何工作?