checkpalindrome.java

来自「此源码为机械工业出版社出版的《Java语言程序设计》第三版所配套的书中所有源代码」· Java 代码 · 共 41 行

JAVA
41
字号
// CheckPalindrome.java: Check whether a string is a palindrome
public class CheckPalindrome
{
  // Main method
  public static void main(String[] args)
  {
    // Prompt the user to enter a string
    System.out.print("Enter a string: ");
    String s = MyInput.readString();

    if (isPalindrome(s))
    {
      System.out.println(s + " is a palindrome");
    }
    else
    {
      System.out.println(s + " is not a palindrome");
    }
  }

  // Check if a string is a palindrome
  public static boolean isPalindrome(String s)
  {
    // The index of the first character in the string
    int low = 0;
    // The index of the last character in the string
    int up = s.length() - 1;

    while (low < up)
    {
      if (s.charAt(low) != s.charAt(up))
        return false; // Not a palindrome

      low++;
      up--;
    }

    return true; // The string is a palindrome
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?