java 数组中的“未找到索引”程序

7kqas0il  于 2023-02-11  发布在  Java
关注(0)|答案(1)|浏览(162)

我写了一个程序,里面有一个数字列表,你需要添加代码才能在列表中找到一个特定的数字,如果找到了这个数字,程序会显示它的位置,如果找不到这个数字,程序会说找不到。
问题是,输出是循环的,我不想要它!谢谢你的指导提前。

array[0] = 6;
        array[1] = 2;
        array[2] = 8;
        array[3] = 1;
        array[4] = 3;
        array[5] = 0;
        array[6] = 9;
        array[7] = 7;

        System.out.print("Search for? ");
        int searching = in.nextInt();

        for(int i=0; i<array.length; i++){
            if(searching == array[i]){
                System.out.println(searching + " is at index " + i + ".");
                break;
            }
            else{
                System.out.println(searching + " was not found.");
            }
        }```

My Output:
Search for? 1
1 was not found.
1 was not found.
1 was not found.
1 is at index 3.

Expected Output:
1 is at index 3.
6tdlim6h

6tdlim6h1#

所以,我已经改变成这样。但是,索引没有找到是不工作。修复我,如果可能的话。:)

int index = 0;
        Boolean yn;
        System.out.print("Search for? ");
        int searching = in.nextInt();

        for(int i=0; i<array.length; i++) {
            if (searching == array[i]) {
                index = i;
                yn = true;
            } else {
                yn = false;
            }
        }

        if(yn=true){
            System.out.println(searching + " is at index " + index + ".");
        }
        else{
            System.out.println(searching + " was not found.");
        }

相关问题