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


    }

}
4
  • 4
    Off-by-one error: Your second loop should start at Wort.length() - 1 instead of Wort.length(). Commented Jul 7, 2017 at 13:16
  • Please start your variable names with a lowercase letter or you'll confuse 99% of java programmers (and syntax highlighters). Commented Jul 7, 2017 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? Commented Jul 7, 2017 at 13:19
  • 1
    I'm tempted to mark this question a dupe of stackoverflow.com/q/18238458/3788176. Commented Jul 7, 2017 at 13:22

3 Answers 3

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); 
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

No joke at the same time i knowed it i changed it right now and then i saw that you writed it im so dumb wtf thanks anyway
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.