[Algorithm java version 02]: Enter a string with the keyboard to determine whether the string is a palindrome

Enter a string by keyboard, and judge whether the string is a palindrome


1. Topic description

Enter a string from the keyboard to determine whether it is a palindrome. For example, 12321 is a palindrome, but 123456 is not a palindrome.

2. Problem-solving ideas

First of all, we need to understand what is a palindrome string. The so-called palindrome string is the same as reading it forward and backward, so we can convert the string into an array of strings, and then compare them in half, that is, head-to-tail comparison , if there is a difference, it is judged not to be a palindrome string, otherwise it is judged to be a palindrome string.

3. Code example

package com.easy.algorithm;

import java.util.Scanner;

/**
 * @ClassName Test02
 * @Description 输入一段字符串,判断是否是回文,例如 12321 就是一个回文,12322 不是一个回文
 * @Author wk
 * @Date 2021/11/12 22:29
 * @Version 1.0
 */
public class Test02 {
    
    
    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
        System.out.println("请输入一段字符串:");
        String str1 = input.next();
        // 字符串转字符数组
        char str2[] = str1.toCharArray();
        // 如果 flag 为 true 则是回文,否则不是 回文
        boolean flag = true;
        for (int i = 0; i < (str2.length / 2); i++) {
    
    
            if (str2[i] != str2[str2.length - i - 1]) {
    
    
                flag = false;
                break;
            }
        }
        if (flag) {
    
    
            System.out.println(str1 + ",是回文");
        } else {
    
    
            System.out.println(str1 + ",不是回文");
        }
    }
}

4. Evaluation results

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/m0_47214030/article/details/121297689