⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 exercise7_1.java

📁 Introduction to java programming 一书中所有编程练习部分的源码
💻 JAVA
字号:
/** Exercise7_1.java:
 *  Rewrite Example 7.1, "Checking Palindromes," which checks
 *  whether a string is a palindrome. Create your own reverse method.
 *   Do not use the reverse method in the StringBuffer class.
 */
import javax.swing.JOptionPane;

public class Exercise7_1 {
  public static void main(String[] args) {
    // Prompt the user to enter a string
    String s = JOptionPane.showInputDialog(null,
                                           "Enter subtotal:",
                                           "Exercise7_1",
                                           JOptionPane.QUESTION_MESSAGE);

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

    System.exit(0);
  }

  /** Check if a string is a palindrome */
  public static boolean isPalindrome(String s) {
    String newString = reverse(s);

    return newString.equals(s);
  }

  /** Reverse a string */
  public static String reverse(String s) {
    String newString = new String();

    for (int i = 0; i < s.length(); i++) {
      newString += s.charAt(s.length() - 1 - i);

    }
    return newString;
  }

  /* Alternative better solution
  public static String reverse(String s) {
    char[] chars = new char[s.length()];

    for (int i = 0; i < chars.length; i++) {
      chars[i] = s.charAt(s.length() - 1 - i);
    }

    return new String(chars);
  }
  */
}

⌨️ 快捷键说明

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