在 Java 中获取“线程“main”java.lang.StringIndexOutOf

输出应该是用自己的行向后打印的数组的每个单词


public class Main

{

    public static void main(String[] args)

    {

         String [] list = {"every", "nearing", "checking", "food", "stand", "value"};

         String reverse = "";

         int length = list.length;

         for(int j=0; j<list.length; j++)

         {

            String word = list[j];

            for ( int i = length - 1 ; i >= 0 ; i-- )

            {

                reverse = reverse + word.charAt(i);

            }

            System.out.println(reverse);

         }


    }

}

但我不断收到这条消息


   Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String 

    index out of range: 5

    at java.lang.String.charAt(String.java:658)

    enter code here`at Main.main(Main.java:13)


智慧大石
浏览 206回答 3
3回答

哆啦的时光机

我稍微清理了你的代码。不要依赖不会提高代码可读性的临时变量。尝试使用for-each循环(它们可以提高可读性)。应用这两点,给我们String[] list = { "every", "nearing", "checking", "food", "stand", "value" };for (String word : list) {&nbsp; &nbsp; for (int i = word.length() - 1; i >= 0; i--) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(word.charAt(i));&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println();}这是基于您的原始代码。就个人而言,我更喜欢使用StringBuilder它的reverse()方法。喜欢,for (String word : list) {&nbsp; &nbsp; System.out.println(new StringBuilder(word).reverse());}或在 Java 8+ 中,map类似Arrays.stream(list).map(s -> new StringBuilder(s).reverse())&nbsp; &nbsp; &nbsp; &nbsp; .forEachOrdered(System.out::println);

慕哥9229398

for ( int i = length - 1 ; i >= 0 ; i-- )length您在上面使用的值是list数组的长度,而不是单词。记住在每个循环后清空反向词:&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(reverse);&nbsp; &nbsp; &nbsp; &nbsp; reverse = "";如果你不冲洗,你会得到:yrevyrevgniraeyrevgniraegnikcehyrevgniraegnikcehdooyrevgniraegnikcehdoodnatyrevgniraegnikcehdoodnateula代替:yrevgniraegnikcehdoodnateula

三国纷争

验证提供的参数在 Main.java:13 中是否有效。检查提供的偏移量是否指向有效索引,并且 count 参数未指向大于字符串本身大小的索引。一个替代:public&nbsp; String[]&nbsp; reverseString(String[] words){&nbsp; &nbsp; String[] reverse=new String[words.length];&nbsp; &nbsp; for(int i=0;i<words.length;i++)&nbsp; &nbsp; {&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; //added for setting element as emptyString instead of null&nbsp; &nbsp; &nbsp; &nbsp; reverse[i] = "";&nbsp; &nbsp; &nbsp; &nbsp; for(int j=words[i].length()-1;j>=0;j--)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; reverse[i]+=words[i].substring(j,j+1);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(Arrays.toString(reverse));&nbsp; &nbsp; return reverse;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java