Home > Java > JavaBase > body text

Java determines whether it is a palindrome number

angryTom
Release: 2019-11-13 14:20:17
Original
3405 people have browsed it

Java determines whether it is a palindrome number

java determines whether it is a palindrome number

The following introduces a simple judgment method, which has been explained in the specific implementation code:

import java.util.*;
public class StringBufferDemo {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //从键盘上输入一个字符串str
        String str = "";
        System.out.println("请输入一个字符串:");
        Scanner in = new Scanner(System.in);
        str = in .nextLine();
        //根据字符串创建一个字符缓存类对象sb
        StringBuffer sb = new StringBuffer(str);
        //将字符缓存中的内容倒置
        sb.reverse();
        //计算出str与sb中对应位置字符相同的个数n
        int n = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == sb.charAt(i))
                n++;
        }
        //如果所有字符都相等,即n的值等于str的长度,则str就是回文。
        if (n == str.length())
            System.out.println(str + "是回文!");
        else
            System.out.println(str + "不是回文!");
    }
}
Copy after login

php Chinese website, a large number of free Java introductory tutorials, welcome to learn online!

The above is the detailed content of Java determines whether it is a palindrome number. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!