Question:
In a string array in java, how would I test each element to see if it's a palindrome?
2012-04-07 22:09:29 UTC
Hi all,

So, i have the array set up and have devised a working test to see if a word is a palindrome or not.

Now, how would I set it up so that my loop takes each element of the array, runs my palindrome test on it, and will print out the words that are the palindromes?

Complete beginner here in intro course. All help is greatly appreciated!
Three answers:
modulo_function
2012-04-07 22:55:49 UTC
You can search for 'java palindrome' here on YA and find plenty of code, including some that I've written.



In the years that I've been here there are questions that appear every day:

prime numbers

fibonacci numbers, with and without recursion

palindrome

..other will come to mind after I post this, I'm sure...



A string is a palindrome if the end chars are the same, and moving in, corresponding chars are the same.



This is a simple test:



boolean paly( String str ) {

...for( int k=0;k
......if( str.charAt(k) != str.charAt(str.length()-k-1 ) return false;

...}

return true;

}



There are lots of ways to do it but the above is simple
Nick
2012-04-08 05:15:47 UTC
The most efficient way to test if any element in your array was a palindrome would be too setup a loop that tests each element and prints the words that are onto the screen. I am a programmer/developer for website design and software development. I work with java a lot and like to use the most efficient ways to do things. Cutting corners never is an option in creating programs, standalone programs, or applets in java. I will not help you by writing the code you need. You need to do that yourself. I am sorry but you need to practice. If you would like when I start video tutorials on YouTube for my company I am going to begin with java so I can throw in how to do your problem in more detail. Good luck. You seem to know the answer to your question.
James Bond
2012-04-08 06:08:09 UTC
Assuming the following is your palindrom function which takes a string and return true if it is palindrome else returns false.

public boolean ispalindrome(String s);



Now, we assume A is string array

for(int i=0;i
if(ispalindrome(A[i])==true) System.out.println(A[i]);


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...