Java(charAt)中的字符串索引超出范围错误 [英] string index out of bounds error in java (charAt)

查看:128
本文介绍了Java(charAt)中的字符串索引超出范围错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速提问.我在程序中有以下代码:

Quick question. I have this code in a program:

input = JOptionPane.showInputDialog("Enter any word below")
int i = 0;  
for (int j = 0; j <= input.length(); j++)  
{
    System.out.print(input.charAt(i));  
    System.out.print(" "); //don't ask about this.  
    i++;
}   

  • 输入为用户输入
  • i 是值为0的整数,如图所示
    • Input being user input
    • i being integer with value of 0, as seen
    • 运行代码会产生此错误:

      Running the code produces this error:

      线程"main"中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:6
      在java.lang.String.charAt(未知来源)
      在program.main(program.java:15)

      Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
      at java.lang.String.charAt(Unknown Source)
      at program.main(program.java:15)

      如果我将 charAt int 更改为0而不是 i ,它不会产生错误...
      该怎么办?有什么问题吗?

      If I change the charAt int to 0 instead of i, it does not produce the error...
      what can be done? What is the problem?

      推荐答案

      替换:

      j <= input.length()
      

      ...和...

      j < input.length()
      

      Java String 字符索引基于0,因此您的循环终止条件应为 input 的长度-1.

      Java String character indexing is 0-based, so your loop termination condition should be at input's length - 1.

      当前,当循环在终止前达到倒数第二次迭代时,它以等于 input 长度的索引引用 input 字符,这将引发 StringIndexOutOfBoundsException(一种 RuntimeException ).

      Currently, when your loop reaches the penultimate iteration before termination, it references input character at an index equal to input's length, which throws the StringIndexOutOfBoundsException (a RuntimeException).

      这篇关于Java(charAt)中的字符串索引超出范围错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆