检查字符串是否对称和回文
我刚刚去了 makeuseof 上的 Symmetrical,它目前位于javascript 和我将其转换为 Java,但是第 38 行(数组)上有一个错误。请检查下面的代码,谢谢。
import java.util.Scanner;
class check
{
public static void main(String args[])
{
String str, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.nextLine();
int length = str.length();
for ( int i = length - 1; i >= 0; i-- )
rev = rev + str.charAt(i);
//Check if Symmetrical
if (isSymmetrical(str)) {
System.out.println(str +" is a symmetrical");
} else {
System.out.println(str +" is not a symmetrical");
}
//Check if palindrome
if (str.equals(rev))
System.out.println(str +" is a palindrome");
else
System.out.println(str +" is not a palindrome");
}
public static boolean isSymmetrical(String str){
double midIndex;
var length = str.length();
if (length % 2 == 0) {
midIndex = Math.floor(length/2);
}
else {
midIndex = Math.floor(length/2) + 1;
}
var pointer1 = 0;
var pointer2 = midIndex;
while(pointer1 < midIndex && pointer2 < length) {
if(str[pointer1] == str[pointer2]) {
pointer1 += 1;
pointer2 += 1;
}
else {
return false;
}
}
return true;
}
}
I just go the Symmetrical at makeuseof and it's currently in javascript and i converted it to Java, However there's an error on the line 38 which is the array. Please check the code below, Thank you.
import java.util.Scanner;
class check
{
public static void main(String args[])
{
String str, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.nextLine();
int length = str.length();
for ( int i = length - 1; i >= 0; i-- )
rev = rev + str.charAt(i);
//Check if Symmetrical
if (isSymmetrical(str)) {
System.out.println(str +" is a symmetrical");
} else {
System.out.println(str +" is not a symmetrical");
}
//Check if palindrome
if (str.equals(rev))
System.out.println(str +" is a palindrome");
else
System.out.println(str +" is not a palindrome");
}
public static boolean isSymmetrical(String str){
double midIndex;
var length = str.length();
if (length % 2 == 0) {
midIndex = Math.floor(length/2);
}
else {
midIndex = Math.floor(length/2) + 1;
}
var pointer1 = 0;
var pointer2 = midIndex;
while(pointer1 < midIndex && pointer2 < length) {
if(str[pointer1] == str[pointer2]) {
pointer1 += 1;
pointer2 += 1;
}
else {
return false;
}
}
return true;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
感谢您分享
string :: charat
这很有帮助,我使用了charat并将double转换为int。
输出:

Thanks to for sharing the
String::charAt
this is very helpfulI used charAt and convert double to int.
Output:
