This task is whether a word is a palindrome, and I use java 11.
After entering of the word with spaces the code gives me an answer, but while loop breaks and the code "finishes with exit code 0" If I choose word = sc.next()
. But If I write word = sc.nextLine()
- It executes well and begins loop again.
I can't understand why, cause I can't debug this part of code, It's just skipped. And I don't understand why this happens. So can somebody explain to me what am I doing wrong?
Maybe there's a way to avoid this spaces?
P.S. I'm new to programming. Thanks to everyone.
try {
Pattern pattern = Pattern.compile("[Y|y][E|e][S|s]");
while (true) {
String word = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter the word without spaces");
if (sc.hasNext("(?>\\p{Alpha})+")) {
word = sc.next();
System.out.println(word);
System.out.println("The word is correct");
String text2;
StringBuilder sb = new StringBuilder();
text2 = sb.append(word).reverse().toString();
if (word.equalsIgnoreCase(text2)) {
System.out.println("Yes, it's a palindrome." + " " + "Want to try another one?");
System.out.println("Enter yes if you want to continue" + " or " + "enter any symbol if no");
if (sc.hasNext(pattern)) {
}
else {
break;
}
}
else {
System.out.println("No, it's not a palindrome." + " " + "Want to try another one?");
System.out.println("Enter yes if you want to continue" + " or " + "enter any symbol if no");
if (sc.hasNext(pattern)) {
}
else {
break;
}
}
}
else {
word = sc.next();
System.out.println("It's not a word");
System.out.println("Want to try another one?");
System.out.println("Enter yes if you want to continue" + " or " + "enter any symbol if no");
if (sc.hasNext(pattern)) {
}
else {
break;
}
}
}
}
catch (NoSuchElementException ex) {
System.out.println(ex.getMessage());
}
}