string index out of bounds error in java (charAt) -
quick question. have code in program:
input = joptionpane.showinputdialog("enter word below") int = 0; (int j = 0; j <= input.length(); j++) { system.out.print(input.charat(i)); system.out.print(" "); //don't ask this. i++; }
- input being user input
i
being integer value of 0, seen
running code produces error:
exception in thread "main" java.lang.stringindexoutofboundsexception: string index out of range: 6
@ java.lang.string.charat(unknown source)
@ program.main(program.java:15)
if change charat
int
0 instead of i
, not produce error...
can done? problem?
replace:
j <= input.length()
... ...
j < input.length()
java string
character indexing 0-based, loop termination condition should @ input
's length - 1.
currently, when loop reaches penultimate iteration before termination, references input
character @ index equal input
's length, throws stringindexoutofboundsexception
(a runtimeexception
).
Comments
Post a Comment