Java程序检查回文
回文一词来源于希腊语“palin dromo”,意思是“再次返回”。一个数字、字符串或短语,当反转时保持不变,即反向读取与正向读取相同,则称为回文。例如,数字回文包括525、2002和12121等数字。而单词回文则有“ABA”、“BABAB”和“RADAR”等。要检查Java中的回文,我们可以使用while循环和if-else块来确定给定的数字或字符串及其反转是否相同。
Java程序检查回文
在本节中,我们将编写不同的Java程序来检查给定的输入是否为回文。在此之前,让我们借助示例来讨论问题陈述。
示例
输入1
121
输出
121 is a Palindrome
输入2
34431
输出
34431 is not a Palindrome
输入3
"ABABA"
输出
ABABA is a Palindrome
现在,让我们进入Java程序来检查回文。
示例1
在本例中,我们将从用户那里获取一个数字作为输入,并检查该数字是否为回文。我们还将借助while循环和if-else条件块。
import java.util.*;
public class Example1 {
public static void main(String[] args) {
// creating an instance of Scanner class
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number to check palindrome: ");
// to take input from user
int num = sc.nextInt();
// copying the original input
int copy = num;
// variable to store the result
int revVal = 0;
// loop to check palindrome
while(copy != 0) {
int rem = copy % 10; // extracting remainder
copy /= 10; // dividing and storing the number
revVal = revVal * 10 + rem; // reversing
}
// checking whether the reverse and original number is same or not
if(num == revVal) {
System.out.println(num + " is a Palindrome number");
} else {
System.out.println(num + " is not a Palindrome number");
}
}
}
输出1
Enter a number to check palindrome: 323 323 is a Palindrome number
输出2
Enter a number to check palindrome: 258 258 is not a Palindrome number
示例2
以下示例说明了如何检查字符串是否为回文。我们将使用StringBuffer类的名为reverse()的内置方法来反转给定的字符串。然后,我们将此反转后的字符串传递给equals()方法,以检查原始字符串和反转后的字符串是否相同。如果两者相同,则字符串为回文,否则不是。
public class Example2 {
public static void main (String[] args) {
String str = "ABABA";
System.out.println("The original String is: " + str);
// reversing the original string
String strRev = new StringBuffer(str).reverse().toString();
// checking whether the reverse is equal to the original string
if (str.equals(strRev)) {
System.out.println(str + " is a Palindrome!");
} else {
System.out.println(str + " is not a Palindrome!");
}
}
}
输出
The original String is: ABABA ABABA is a Palindrome!
示例3
这是另一个Java程序,用于检查给定的数字是否为回文。
public class Example3 {
public static void main(String[] args) {
int num = 52525;
System.out.println("The original number is: " + num);
// copying the original input
int copy = num;
// variable to store the result
int revVal = 0;
// loop to check palindrome
while(copy != 0) {
int rem = copy % 10; // extracting remainder
copy /= 10; // dividing and storing the number
revVal = revVal * 10 + rem; // reversing
}
// checking whether the reverse and original number is same or not
if(num == revVal) {
System.out.println(num + " is a Palindrome number");
} else {
System.out.println(num + " is not a Palindrome number");
}
}
}
输出
The original number is: 52525 52525 is a Palindrome number
结论
在本文中,我们学习了Java中的回文。此外,我们还讨论了不同的Java程序,这些程序说明了如何检查给定的输入是否为回文。实现此目的最直接的方法是使用StringBuffer类的名为reverse()的内置方法。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP