用Java语言写一个程序,要求:输入一个以回车符为结束标志的字符串,判断该字符串是否为回文。是则输出yes,否则输出NO 要利用一维字符组实现字符串的存储与运算
时间: 2024-11-29 19:33:52 浏览: 46
好的,下面是一个简单的Java程序,它使用了一维字符数组来实现字符串的存储,并通过反转字符串的方式判断其是否为回文:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个字符串(以回车符结束):");
// 获取用户输入并存储在一维字符数组中
char[] inputString = new char[scanner.nextLine().length()];
for (int i = 0; i < inputString.length; i++) {
inputString[i] = scanner.nextLine().charAt(i);
}
// 判断字符串是否为回文
boolean isPalindrome = checkPalindrome(inputString);
if (isPalindrome) {
System.out.println("yes");
} else {
System.out.println("NO");
}
scanner.close();
}
// 检查字符串是否为回文
private static boolean checkPalindrome(char[] chars) {
int left = 0;
int right = chars.length - 1;
while (left < right) {
if (chars[left] != chars[right]) {
return false;
}
left++;
right--;
}
return true;
}
}
```
在这个程序中,我们首先获取用户的输入并存储在一个字符数组中。然后,`checkPalindrome`函数通过比较数组两端的字符是否相等来判断字符串是否为回文。如果所有对称的字符都匹配,则字符串是回文。
阅读全文
相关推荐


















