以下是一个简单的JAVA程序,从命令行参数中读入一个字符串,使用reverse方法检查该字符串是否为回文串:

public class Palindrome {
    public static void main(String[] args) {
        if(args.length != 1) {
            System.out.println("Usage: java Palindrome <string>");
            return;
        }
        String s = args[0];
        String reverse = new StringBuilder(s).reverse().toString();
        if(s.equals(reverse)) {
            System.out.println(s + " is a palindrome");
        } else {
            System.out.println(s + " is not a palindrome");
        }
    }
}

运行该程序时,需要在命令行中输入一个字符串作为参数,例如:

java Palindrome racecar

输出结果为:

racecar is a palindrome

如果输入的字符串不是回文串,输出结果为:

hello is not a palindrome

标签: 教育


原文地址: https://cveoy.top/t/topic/biG1 著作权归作者所有。请勿转载和采集!