java - 返回整数数组中特定值的索引

标签 java arrays

Write a method named indexOf that returns the index of a particular value in an array of integers. The method should return the index of the first occurrence of the target value in the array. If the value is not in the array, it should return -1. For example, if an array called list stores the following values:

int[] list = {42, 7, -9, 14, 8, 39, 42, 8, 19, 0};

Then the call indexOf(list, 8) should return 4 because the index of the first occurrence of value 8 in the array is at index 4. The call indexOf(list, 2) should return -1 because value 2 is not in the array.

当答案需要为 -1 时,我的尝试不起作用。

 public int indexOf(int[] arr,int value) {
        int k=0;
        for(int i=0;i<arr.length;i++){
            if(arr[i]==value){
                k=i;
                break;
            }
        }
    return k;
}

最佳答案

k初始化为-1而不是0

关于java - 返回整数数组中特定值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49107663/

相关文章:

java - 类路径在 linux 下不起作用

Java JTextPane 向 JScrollPane 添加空白区域

javascript - 观察者模式问题 - JavaScript 对象从父数组中删除自身?

javascript - 如何显示 Elements 数组的对象类型

arrays - 从字符串中删除元素+将其转换为数组

Char* 从 char 数组中解析错误

java - 更新 map 并阅读时锁定免费解决方案

java - 我无法使用actionPerformed()方法处理JButton点击事件,不要进入该方法,为什么?

java - 在 BottomNavigationView 中开始 fragment

javascript - 从数组中随机选择对象