I wrote the java code to find out whether the string is a palindrome or not. But, I am not getting the required result. Please suggest necessary change in code.
public class Test1
{
public static void main(String[] args)
{
String original="madam";
String rev="";
int len=original.length();
System.out.println(len);
boolean flag=false;
for(int i=len-1,j=1;i>0;i--,j++)
{
if(original.charAt(i)==original.charAt(j))
{
flag=true;
continue;
}
else
{
flag=false;
break;
}
}
if(flag)
System.out.println("palindrome");
else
System.out.println("not a polindrom");
}
}
Try this:
public class Test1
{
public static void main(String[] args)
{
String original="madam";
int len=original.length();
System.out.println(len);
boolean flag=true;
for(int i=len-1,j=0;i != j;i--,j++)
{
if(original.charAt(i) != original.charAt(j))
{
flag=false;
break;
}
}
if(flag)
System.out.println("palindrome");
else
System.out.println("not a polindrom");
}
}
This will work for you.
It uses the reverse()
method of class java.lang.StringBuilder
public class Test1 {
public static void main(String[] args) {
String original = "madam";
StringBuilder sb = new StringBuilder(original);
String reverse = sb.reverse().toString();
if (original.equals(reverse)) {
System.out.println("PALINDROME");
} else {
System.out.println("NOT A PALINDROME");
}
}
}
Strings are zero-indexed in Java. This means that your j
variable is starting at the second character in the string.
Try changing the for
loop header to this:
for(int i=len-1,j=0;i>j;i--,j++)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.