I was going through a Palindrome( Specifically String Palindrome) Problem and was checking whether the string is palindrome or not. But a problem struck in the program
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
int n,flag=0;
n=sc.nextInt();
char a[]=new char[n];
int l=0;
int h=n-1;
while(l<h)
{
if(a[l++]!=a[h--])
{
flag=1;
}
}
if(flag==1)
{
System.out.println("String is not Palindrome");
}
else{
System.out.println("String is Palindrome");
}
}
So above is the code which I wrote but the problem is, I have created a character array instead of the string. The main point of the argument is the above code correct in terms of code standards.
is the above code correct in terms of code standards
Not really:
Don't name a local variable l
(lowercase L). It is too easy to confuse with 1
(one).
Since I don't know what h
is supposed to be a shorthand for, I changed l
and h
to i
and j
below, as those are very common integer iterator variable names.
Don't declare a local variable before it's needed. Use int n = sc.nextInt();
Don't put array declaration on the variable name. Put it on the type, since it defines the type.
Don't use 0
/ 1
for false
/ true
values. Change flag
to a boolean
, and name it better, e.g. describe its value. notPalindrome
seems appropriate here. It helps document the code.
The while
loop should be a for
loop. It helps keeping loop logic together, and isolated from other logic, and it helps limit the scope of the loop variable(s).
Those were my comments related to coding standards.
However, your code doesn't work, because you never get a string from the user. Your choice of using char[]
is fine, but you need to change the logic for getting it. See code below for how to use toCharArray()
to do that.
Also, once a difference is found, you should exit the loop, either by also checking the boolean variable in the loop condition, or by using break
. Personally, I prefer break
.
Scanner sc = new Scanner(System.in);
String sentence = sc.nextLine();
char[] a = sentence.toCharArray();
boolean notPalindrome = false;
for (int i = 0, j = a.length - 1; i < j; i++, j--) {
if (a[i] != a[j]) {
notPalindrome = true;
break;
}
}
if (notPalindrome) {
System.out.println("String is not Palindrome");
} else {
System.out.println("String is Palindrome");
}