Ich habe mich an einem Programm versucht, dass ein Wort darauf überprüft, ob diese ein Palindrom ist. Mein zeigt jedoch folgende Fehlermeldungen an:
Das ist mein Code:
Vielen Dank für Eure Zeit
Code:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:711)
at kleineProjekte.checkPalindrome.<init>(checkPalindrome.java:37)
at kleineProjekte.checkPalindrome.main(checkPalindrome.java:10)
Das ist mein Code:
Code:
package kleineProjekte;
public class checkPalindrome {
String word = "oma";
StringBuilder sb1;
StringBuilder sb2;
public static void main(String[] args) {
new checkPalindrome();
}
public checkPalindrome() {
if(checkEven() == true){
sb1 = new StringBuilder("");
sb2 = new StringBuilder("");
for(int i = 0; i<word.length()/2; i++) {
//appends a string from the first half of 'word'
sb1.append(word.charAt(i));
}
for(int i = word.length(); i>word.length()/2; i--) {
sb2.append(word.charAt(i));
//appends a string from the second half of 'word' but backwards
}
if(sb1 == sb2) {
//checks both appended Strings
System.out.println("word is a palindrome");
}
else {
System.out.println("word isnt a palindrome");
}
}
else {
sb1 = new StringBuilder("");
sb2 = new StringBuilder("");
for(int i = 0; i<(word.length()-1)/2; i++) {
//appends a String from the first half of a word-1: tomot --> to
sb1.append(word.charAt(i));
}
for(int i = word.length(); i>(word.length()+1)/2; i--) {
//appends a String from the first half of a word+1: tomot --> to
sb2.append(word.charAt(i));
}
if(sb1 == sb2) {
System.out.println("word is a palindrome");
}
else {
System.out.println("word isnt a palindrome");
}
}
}
public boolean checkEven() {
//checks whether 'word' is even
if(word.length()%2==0) {
return true;
}
else {
return false;
}
}
}
Vielen Dank für Eure Zeit