-5
["Exception in thread "main" 
java.lang.StringIndexOutOfBoundsException: String index out of range: 2
    at java.lang.String.charAt(Unknown Source)
    at Haupt.main(Haupt.java:21)"]

And here is my code. Why did I get this error?

import java.util.Scanner;

public class Haupt {

    public static void main(String[] args) {
        String Wort="";
        String WortCpy="";
        String WortRev="";
        int i=0;
        Scanner scan = new Scanner(System.in);


        System.out.print("Geben Sie ein Wort ein : "); //Ausgabe
        Wort = scan.nextLine(); //Eingabe
        scan.close();
        for(i=0;i < Wort.length();i++) { 
            WortCpy= WortCpy +  Wort.charAt(i); //Speichert jeden Buchstaben einzeln in Wortcpy ab
        }
        for(i=Wort.length();i>=0;i--) {
            WortRev = WortRev +  Wort.charAt(i); 
        }

        System.out.println("Wort : " + Wort);
        System.out.println("Wort Kopiert : " + WortCpy);
        System.out.println("Wort umgedreht : " + WortRev);


    }

}
halfer
  • 19,824
  • 17
  • 99
  • 186
  • 4
    Off-by-one error: Your second loop should start at `Wort.length() - 1` instead of `Wort.length()`. – Jesper Jul 07 '17 at 13:16
  • Please start your variable names with a lowercase letter or you'll confuse 99% of java programmers (and syntax highlighters). – byxor Jul 07 '17 at 13:19
  • With code `for(i=Wort.length(); ...) {... Word.charAt(i)... }` part `Word.charAt(i)` will at first iteration behave like `Word.charAt(Word.length())`. Do you see the problem now? – Pshemo Jul 07 '17 at 13:19
  • 1
    I'm tempted to mark this question a dupe of https://stackoverflow.com/q/18238458/3788176. – Andy Turner Jul 07 '17 at 13:22

3 Answers3

0

Indexes start from 0 for a String object. So you have not index which number equals to Wort.length()

Try this;

 for(i=Wort.length()-1;i>=0;i--) {
        WortRev = WortRev +  Wort.charAt(i); 
    }
Mustafa Çil
  • 766
  • 8
  • 15
0

String.length() returns the length of the string, but with zero based indexes, you cannot use this as a character index. Try something like this:

for ( i = Wort.length()-1; i >= 0; i-- )
{
    WortRev = WortRev +  Wort.charAt(i); 
}
Usagi Miyamoto
  • 6,196
  • 1
  • 19
  • 33
0

Where you are looping from wort.length() through to 0 (and vice versa) you need to use wort.length() - 1.

This is because the strings char array is 0 indexed (meaning that the first char is at index 0 and the last char is at length - 1). So by this logic, in your code, when the loop hits the point where i = wort.length() then you'll get array out of bounds error.

Thomas Cook
  • 4,371
  • 2
  • 25
  • 42