试图返回数组中某个元素的位置,打印时遇到问题

我正在处理此代码以打印此数组中的位置,并且我认为在获取返回值时我的所有代码都是正确的,但是我无法获取任何值;打印在屏幕上。我尝试调用 arrayLength 方法进行打印,但我得到的只是错误“arrayLength 无法解析为变量”。所以我不确定要打印什么变量。


 public class Generics {

        static List<Integer> list = new ArrayList<Integer>();

        Integer[] array = {2, 4, 6, 8};

        Integer s= list.get(0);


         int arrayLength(int[] array, int value) {


        for (int i = 0; i < array.length; i++) {


            if(array[i]==value) {

                return i;

            }

        }

        return -1;

        }


        public static void main(String[] args) {

           System.out.println(arrayLength);

        }

      }


繁花不似锦
浏览 102回答 2
2回答

莫回无

我相信您正在尝试打印函数而不是返回值。如果System.out.println(arrayLength);用System.out.println(arrayLength(array, 4));&nbsp;它替换应该打印数组中的索引 4同样如评论中所述,arrayLength 方法需要是静态的才能从 main 方法中调用

守着一只汪

注意:整数 s= list.get(0); 给出 IndexOutOfBoundsException 因为列表是空的所以不可能检索第一个元素public class Generics {&nbsp; &nbsp; &nbsp; &nbsp; static int[] array = {2, 4, 6, 8};&nbsp; &nbsp; &nbsp; &nbsp; static int arrayLength(int[] array, int value) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < array.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(array[i]==value) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return i;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return -1;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(arrayLength(array, 2));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(arrayLength(array, 4));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(arrayLength(array, 6));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(arrayLength(array, 8));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java