0
trying out palindrome in java : 1) I cant get it right. 2) variable c isn't incrementing . Can someone help me out.
import java.util.Scanner; public class palindrome { public static void main(String [] args) { int c=0; String name; Scanner sc = new Scanner(System.in); System.out.println("Enter the word"); name = sc.next(); String a[]=name.split(""); int x=a.length; for(int i=0;i<x/2;i++) { if(a[i]!=a[x-1-i]) { break; } c++; } System.out.println(c); if(c==x/2) { System.out.println("it is a palindrome"); } else { System.out.println("Not palindrome"); } System.out.println(c); } }
10 ответов
+ 10
Do as visph has suggested or you can do
// if(a[i]!=a[x-1-i]) {
if(! a[i].equals(a[x-1-i])) {
+ 4
You're not using the right way of comparing String array items:
// if(a[i]!=a[x-1-i]) {
if(a[i].compareTo(a[x-1-i])!=0) {
;)
+ 3
/*
To improve your code, you could use a boolean as suggested by @Oleg, but you can also do it by this way (I keep your previous fixed code in comments):
*/
import java.util.Scanner;
public class palindrome {
public static void main(String [] args)
{
// int c=0;
String res = "";
String name;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the word");
name = sc.next();
String a[]=name.split("");
int x=a.length;
for(int i=0;i<x/2;i++)
{
if(a[i].compareTo(a[x-1-i])!=0) {
res = "not ";
break;
}
//c++;
}
System.out.println("it is "+res+"a palindrome");
/*
System.out.println(c);
if(c==x/2)
{
} else {
System.out.println("Not palindrome");
}
*/
// System.out.println(c);
}
}
+ 3
@Joseph wrote: << does equals method return something like an integer value other than true and false like compareTo method >>
I supposed it's returning a boolean value, avoiding needs of comparison ;)
+ 2
@Oleg:
Question was not to improve that code, but fix the error... and the error is that (a[i]!=a[x-i-1]) return always true (comparing references instead values) ^^
+ 1
@vaibhav
Thanks dude and does equals method return something like an integer value other than true and false like compareTo method
0
Thanku visph. I got it and now realize that Strings can't be compared in the same way as other DT's.
0
@Oleg
Thanku for giving me an idea beyond my doubt. I'm just getting started in programming and truly value ur help. Much obliged.
- 1
Take a look on my approaches, fellow:
https://code.sololearn.com/c8OLa6oPvk6V/?ref=app
https://code.sololearn.com/cKX1twtIeLb0/?ref=app
- 1
Here are my new tries, now using Python:
https://code.sololearn.com/ckzKZUhvplvr/?ref=app
https://code.sololearn.com/cdb28fBq2f90/?ref=app