3

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?

blackpanther
  • 10,998
  • 11
  • 48
  • 78
Kyle
  • 299
  • 1
  • 2
  • 11

7 Answers7

9

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

Mena
  • 47,782
  • 11
  • 87
  • 106
3

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

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

0

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++;
}
Guillermo Merino
  • 3,197
  • 2
  • 17
  • 34
0

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++;
} 
blackpanther
  • 10,998
  • 11
  • 48
  • 78
Benjamin
  • 2,257
  • 1
  • 15
  • 24
0

Use this;

for (int j = 0; j < input.length(); j++)
{
    System.out.print(input.charAt(j));
    System.out.print(" "); //don't ask about this.
}
blackpanther
  • 10,998
  • 11
  • 48
  • 78
Hüseyin BABAL
  • 15,400
  • 4
  • 51
  • 73
0
for (int j = 0; j < input.length(); j++)
{
    System.out.print(input.charAt(j));
    System.out.print(" "); //don't ask about this.
}
nikis
  • 11,166
  • 2
  • 35
  • 45