[英]Check string if Symmetrical and palindrome
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.我只是 go 在makeuseof的对称,它目前在 javascript 中,我将它转换为 Java,但是第 38 行是数组的错误。 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;
}
}
Thanks to for sharing the String::charAt
this is very helpful感谢分享
String::charAt
这非常有帮助
I used charAt and convert double to int.我使用 charAt 并将 double 转换为 int。
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;
int length = str.length();
if (length % 2 == 0) {
midIndex = Math.floor(length/2);
}
else {
midIndex = Math.floor(length/2) + 1;
}
int pointer1 = 0;
double pointer2 = midIndex;
while(pointer1 < midIndex && pointer2 < length) {
if(str.charAt(pointer1) == str.charAt((int)pointer2)) {
pointer1 += 1;
pointer2 += 1;
}
else {
return false;
}
}
return true;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.