简体   繁体   中英

string index out of bounds error in 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++;
}   
  • Input being user input
  • i being integer with value of 0, as seen

Running the code produces this error:

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)

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?

Replace:

j <= input.length()

... with ...

j < input.length()

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

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 ).

String indexing in Java (like any other array-like structure) is zero-based . This means that input.charAt(0) is the leftmost character. The last character is then at input.charAt(input.length() - 1) .

So you are referencing one too many elements in your for loop. Replace <= with < to fix. The alternative ( <= input.length() - 1 ) could bite you hard if you ever port your code to C++ (which has unsigned types).

By the way, the Java runtime emits extremely helpful exceptions and error messages. Do learn to read and understand them.

Replace for loop condition j <= input.length() with j < input.length() , as string in Java follows zero based indexing. eg indexing for the String "india" would start from 0 to 4.

You were accessing the array from [0-length], you should do it from [0-(length-1)]

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++;
}

Try the following:

j< input.length() 

and then:

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++;
} 

Use this;

for (int j = 0; j < input.length(); j++)
{
    System.out.print(input.charAt(j));
    System.out.print(" "); //don't ask about this.
}
for (int j = 0; j < input.length(); j++)
{
    System.out.print(input.charAt(j));
    System.out.print(" "); //don't ask about this.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM