本文介绍了数组索引越界异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 此代码应返回数组中最长字符串的长度。我不知道如何做到这一点或修复此错误。我不明白该方法的工作部分。有什么建议/帮助吗?提前致谢。 public static double 最长(字符串 [] A){ int max = 0 ; for ( int i = 0; i< A.length; i ++){ if (A [i] .length()< A [i ++] .length()){ max = A [i] .length (); } else max = A [i ++] .length(); } 返回 max; } public static void main( String [] args){ String [ ] S2 = { H, 嗨, 嘿嘿, 嘿!}; System.out.println(最长(S2)); } } 线程中的异常 main java.lang.ArrayIndexOutOfBoundsException: 4 at fixMyCode.longest(fixMyCode.java: 8 )fixMyCode.main的(fixMyCode.java: 15 ) 我尝试了什么: 我试过搞乱for语句本身,但我不知道是什么我正在做。解决方案 错误消息id因为i ++改变了值我和你在数组结束后结束。 你的算法是完全错误的,你没有通过比较数组的2个连续元素来获得最大长度。 你通过比较元素的长度与当前最大值来获得最大长度 This code is supposed to return the length of the longest string in an array. I'm not sure how to make it do that or fix this error. I don't understand the working parts of the method. Any suggestions/help? Thanks in advance. public static double longest(String[] A) { int max = 0; for (int i=0; i<A.length; i++) { if (A[i].length() < A[i++].length()) { max = A[i].length(); } else max = A[i++].length(); } return max; } public static void main(String[] args) {String[] S2 = {"H", "Hi", "Hey", "Hey!"}; System.out.println(longest(S2)); }}Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at fixMyCode.longest(fixMyCode.java:8) at fixMyCode.main(fixMyCode.java:15)What I have tried:I've tried messing with the for statement itself, but I don't know what I'm doing. 解决方案The error message id because i++ change the value of i and you endup after the end of array.Your algorithm is plain wrong, you don't get the maximum length by comparing 2 consecutive elements of an array.You get max length by comparing length of an element with current max. 这篇关于数组索引越界异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 09-02 08:42