回文 - 试图弄清楚如何使 while 循环声明完全错误,即使其中一个测试出现在 else 或 "not a palindrome"

Palindrome -Trying to figure out how to make the while loop declare completely false if even one of the tests comes out to else or "not a palindrome"

System.out.println("Please type a phrase below and see if its a palindrome:");  
    Scanner keyboard = new Scanner(System.in);  
    String phrase = keyboard.nextLine(); //0-7 char

    int counter = 0; //0-7,1-6,2-5,3-4
    String is = "";
    int caseo;

    while (counter < phrase.length()) {
        int num = phrase.length() - (counter) - 1;
        char a = phrase.charAt(counter);
        char b = phrase.charAt(num);
        ++counter;
            if (a == b) {
                is = "a palindrome";
        } 
            else {
                is = "not a palindrome";
        }               
            System.out.println("is " + is); 
        }

您的代码有几个问题,我会尝试在更正后的版本上进行解释。我更喜欢在单独的方法中使用 for 循环,但是由于您的问题是关于 while 循环的,所以我们就拿它来说吧。

System.out.println("Please type a phrase below and see if its a palindrome:");
Scanner keyboard = new Scanner(System.in);
String phrase = keyboard.nextLine();
keyboard.close(); // the Scanner is not re-used later, we can close it here

int counter = 0;

// consider each String (also empty) to be a palindrome,
// unless proven otherwise later on
boolean isPalindrome = true;

// it is enough to loop over n/2 characters,
// otherwise you check each pair twice
int maxIndex = phrase.length() / 2;

while (counter < maxIndex) {
    int num = phrase.length() - (counter) - 1;

    char a = phrase.charAt(counter);
    char b = phrase.charAt(num);

    ++counter;

    // we found two characters that do not match
    if (a != b) {
        // so we remember the answer
        isPalindrome = false;

        // and exit the loop since the answer cannot be "true" anymore
        break;
    }
}

// here we just check the result and print the answer
// please note that this is done outside of the loop
if (isPalindrome) {
    System.out.println("is a palindrome");
} else {
    System.out.println("is not a palindrome");
}