problème sur un palindrome
bonjour j ai un problème sur le code si je rentre une phrase avec des espaces ,il y a l'erreur "String index out of bounds exeption" sinon tout va bien
code:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| import java.util.Scanner;
public class Palindrome {
static Scanner clavier = new Scanner(System.in);
public static void main(String[] args) {
//on entre une phrase au clavier
System.out.println("Veuillez entrer une phrase :");
String phrase = clavier.nextLine();
//on garde que les lettres de l alphabet
String temp = "";
for (int i = 0; i < phrase.length(); i++) {
char c = phrase.charAt(i);
if(Character.isLetter(c) ) {
//on récupère les caractères dans l'objet temporaire
temp += c;
}
}//on met tout en minuscule et on le stock dans l objet test
String test = temp.toLowerCase();
System.out.println(test);
//on initialise les variables pour le test
int leftpos = 0;
int rightpos =phrase.length()-1;
boolean palindrome = true;
// on commence le test avec une boucle
while ((leftpos<rightpos) && palindrome){
if(test.charAt(leftpos) == test.charAt(rightpos)) {
palindrome = true;
leftpos++;
rightpos--;
}else {
palindrome = false;
}
}if(palindrome) {
System.out.println("c'est un palindrome");
}else {
System.out.println("Non ce n'est pas un palindrome");
}
}
} |
je l avais réalisé ,il marchait,j 'ai tout refait pour comprendre le code et après l avoir refait il y a eu cette erreur comme quoi je dépasse l index ?? apparemment quelque chose m ''échappe..
merci pour vos réponses.