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); } }

10th Jul 2017, 5:51 AM
Joseph Nithish
Joseph Nithish - avatar
10 Respuestas
+ 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])) {
10th Jul 2017, 6:41 AM
Vaibhav Sharma
Vaibhav Sharma - avatar
+ 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) { ;)
10th Jul 2017, 6:17 AM
visph
visph - avatar
+ 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); } }
10th Jul 2017, 7:13 AM
visph
visph - avatar
+ 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 ;)
10th Jul 2017, 7:14 AM
visph
visph - avatar
+ 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) ^^
10th Jul 2017, 6:37 AM
visph
visph - avatar
+ 1
@vaibhav Thanks dude and does equals method return something like an integer value other than true and false like compareTo method
10th Jul 2017, 6:59 AM
Joseph Nithish
Joseph Nithish - avatar
0
Thanku visph. I got it and now realize that Strings can't be compared in the same way as other DT's.
10th Jul 2017, 6:54 AM
Joseph Nithish
Joseph Nithish - avatar
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.
10th Jul 2017, 6:56 AM
Joseph Nithish
Joseph Nithish - avatar
8th Dec 2017, 11:32 PM
Jonathan Álex
Jonathan Álex - avatar
9th Dec 2017, 11:33 AM
Jonathan Álex
Jonathan Álex - avatar