I am a student trying to get this palindrome checker to reflect back if the entered strings are indeed a palindrome or not. I keep returning just one result and I cannot figure out why. Not sure if I am missing something from my loop or if I have something incorrect in my loop here.
public class Palindrome {
public static void main(String[] args) {
System.out.println("Palindrome Checker: ");
palindromChecker("aabaa", "cat", "racecar", "dog", "Madam");
}
public static void palindromChecker(String... values) {
String stbr = "";
String reverse = " ";
for (int i = stbr.length() - 1; i >= 0; i--)
reverse += stbr.charAt(i);
if (reverse.equalsIgnoreCase(stbr))
System.out.println("This is a Palindrome");
else {
System.out.println("This is NOT a Palindrome");
}
}
}
You aren't actually looping through the input values from your array values. What you are doing is trying to reverse stbr which you assigned to be an empty String. You want to do something like this:
public class Palindrome {
public static void main(String[] args) {
System.out.println("Palindrome Checker: ");
palindromChecker("aabaa", "cat", "racecar", "dog", "Madam");
}
public static void palindromChecker(String... values) {
for (String stbr : values) {
String reverse = "";
for (int i = stbr.length() - 1; i >= 0; i--) {
reverse += stbr.charAt(i);
}
if (reverse.equalsIgnoreCase(stbr)) {
System.out.println("This is a Palindrome");
} else {
System.out.println("This is NOT a Palindrome");
}
}
}
}
for (String stbr : values) { loops through every element in values one at a time, allowing you to reverse and check each element of your input.
Related
i have a programming task using java...
public class CountWords{
public static void main(String[] args) {
String sentence = "Papa beauty lies in the eyes of beholder";
int wordcount = 0;
for(int i = 0; i < sentence.length()-1; i++) {
if(sentence.charAt(i) == ' ' && Character.isLetter(sentence.charAt(i+1)) && (i > 0)) {
wordcount++;
}
}
wordcount++;
System.out.println("Total number of words: " + wordcount);
System.out.println(sentence.startsWith("P"));
}}
My question is how can i define the String sentence based on this condition:
If more than 3 words, it will be True.
If less than 4 words, it becomes False.
Thankyou so much for helping..
If I understand your question correctly...
/* returns string array of tokens (words in the sentence) after splitting by space */
String[] tokens = sentence.split(" ");
if(tokens.length() > 3) {
// true
} else {
// fasle
}
Let's have a look at the steps we should take in order to achieve your goal in a easier way;
First , let's count the number of words in your input string via
count function
Call the function by sending our input sentence
Function returns number of words Check the number of words for any
condition you desire
Therefore your code will work better like this;
public class CountWords{
public static void main(String[] args) {
String sentence = "Papa beauty lies in the eyes of beholder";
private bool coniditon;
int wordcount = count(sentencte);
if (wordcount<4) {
condition=False;
}
else if (wordcount>3) {
condition=True;
}
System.out.println("Total number of words: " + wordcount);
System.out.println(sentence.startsWith("P"));
}
public static int count(String sentence){
if(sentence == null || sentence.isEmpty()){
return 0; }
String[] words = sentence.split("\\s+");
return words.length; }
}
}
Good luck!
suppose we have
String str = "Hello-Hello1";
How do we split it and compare it to see if it is equal or not?
This is what I wrote, but it does not give me the result.
public static void main(String[] args) {
String str = "Hello-Hello1";
String [] a = str.split("-");
for(int i=0; i<a.length; i++) {
System.out.print(a[i]+ " ");
}
for(int first =0; first<a.length; first++) {
for(int second =first+1; second<a.length; second ++) {
if(a[first].equals(a[second])){
System.out.println(a[first]);
}
}
}
}
First, you split your string like shown here:
How to split a string in Java, then compare them using the equals method: a[0].equals(a[1]);
Thank you all for helping
Here is the answer
public class SplitStringAndCompare {
public static void main(String[] args) {
String str = "Hello-Hello1";
String [] a = str.split("-");
if(a[0].equals(a[1])) {
System.out.println(a[0]+ " is equal to " + a[1]);
} else {
System.out.println(a[0]+ " is not equal to "+ a[1]);
}
}
Today I am trying to convert String to reverse String e.g(Cat Is Running into Running Is Cat) word by word not Character
public class ReverseString_ {
public static void reverse(String str) {
String[] a = str.split(" ");
for (int i = a.length - 1; i >= 0; i--) {
System.out.println(a[i] + " ");
}
}
public static void main(String[] args) {
reverse("Cat Is Running");
}
}
The following output is shown:
Running Is Cat BUILD SUCCESSFUL (total time: 0 seconds)
I am trying to convert String into reverse String same as above but through Recursion method but it seems too confusing. and display more errors. Can someone please help me understanding it. Many thanks
public static String reverse_recursion(String str) {
if (str == null)
return null;
else {
String Arry[] = str.split(" ");
int n = Arry.length - 1;
System.out.println(Arry[n] + "");
return reverse_recursion(Arry[n - 1]);
}
}
public static void main(String[] args) {
reverse_recursion("Cat Is Running");
}
This code show following output:
Running
Is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
This code do not print (0) index why? can someone help me to solve this error please
This solution might be helpful. The comments explain the code pretty much.
public static String reverse_recursion(String str) {
String[] arry = str.split(" ", 2); //Split into a maximum of 2 Strings
if (arry.length > 1) { //If there is more than 1 word in arry
//Return the reverse of the rest of the str (arry[1])
//and concatenate together with the first word (arry[0])
return reverse_recursion(arry[1]) + " " + arry[0];
}
return arry[0]; //If less than or equal to 1 word, just return that word
}
This should work:
public static String reverse(String s) {
int idx = s.indexOf(" ");
if (idx < 0) {
// no space char found, thus, s is just a single word, so return just s itself
return s;
} else {
// return at first the recursively reversed rest, followed by a space char and the first extracted word
return reverse(s.substring(idx + 1)) + " " + s.substring(0, idx);
}
}
public static void main(String[] args) {
System.out.println(reverse("Cat Is Running"));
}
You are sending the last element of the Array next time instead of the String without the previously printed String.
Replace your return statement with this it should work.
return reverse_recursion(n==0?null:str.substring(0,(str.length()-Arry[n].length())-1));
/*Match pattern ab in the pattern ababbaba and print the number of times ab is in the pattern , and also print the index value of a in ab*/
package stringmatch;
public class StringMatch {
public static void main(String[] args) {
String name="ababbaba";
int len,index=0,count=0,temp=0,in,i=index+1;
String m;
char ch,c;
// String match="ab";
len=name.length();
for(index=0;index<=len-1;index++)
{
ch=name.charAt(index);
if(name.charAt(index)=='a'&&name.charAt(i+1)=='b')
{
count++;
temp=index;
System.out.println("ab is "+count+" "+"index is "+temp);
//i++;
}
}
} //System.out.println(count+" ");
}
You could rewrite your code as follows,
String name="ababbaba";
int len, count=0;
// String match="ab";
len=name.length();
for(int index=0; index<=len-2;index++)
{
if(name.charAt(index)=='a' && name.charAt(index+1)=='b')
{
count++;
System.out.println("ab is "+count+" "+"index is "+ index);
}
}
This question already has answers here:
Check string for palindrome
(42 answers)
Closed 7 years ago.
I want to check if a string is a palindrome or not. I would like to learn an easy method to check the same using least possible string manipulations
Using reverse is overkill because you don't need to generate an extra string, you just need to query the existing one. The following example checks the first and last characters are the same, and then walks further inside the string checking the results each time. It returns as soon as s is not a palindrome.
The problem with the reverse approach is that it does all the work up front. It performs an expensive action on a string, then checks character by character until the strings are not equal and only then returns false if it is not a palindrome. If you are just comparing small strings all the time then this is fine, but if you want to defend yourself against bigger input then you should consider this algorithm.
boolean isPalindrome(String s) {
int n = s.length();
for (int i = 0; i < (n/2); ++i) {
if (s.charAt(i) != s.charAt(n - i - 1)) {
return false;
}
}
return true;
}
For the least lines of code and the simplest case
if(s.equals(new StringBuilder(s).reverse().toString())) // is a palindrome.
Here is a simple one"
public class Palindrome {
public static void main(String [] args){
Palindrome pn = new Palindrome();
if(pn.isPalindrome("ABBA")){
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
}
public boolean isPalindrome(String original){
int i = original.length()-1;
int j=0;
while(i > j) {
if(original.charAt(i) != original.charAt(j)) {
return false;
}
i--;
j++;
}
return true;
}
}
You can try something like this :
String variable = ""; #write a string name
StringBuffer rev = new StringBuffer(variable).reverse();
String strRev = rev.toString();
if(variable.equalsIgnoreCase(strRev)) # Check the condition
Here's a good class :
public class Palindrome {
public static boolean isPalindrome(String stringToTest) {
String workingCopy = removeJunk(stringToTest);
String reversedCopy = reverse(workingCopy);
return reversedCopy.equalsIgnoreCase(workingCopy);
}
protected static String removeJunk(String string) {
int i, len = string.length();
StringBuffer dest = new StringBuffer(len);
char c;
for (i = (len - 1); i >= 0; i--) {
c = string.charAt(i);
if (Character.isLetterOrDigit(c)) {
dest.append(c);
}
}
return dest.toString();
}
protected static String reverse(String string) {
StringBuffer sb = new StringBuffer(string);
return sb.reverse().toString();
}
public static void main(String[] args) {
String string = "Madam, I'm Adam.";
System.out.println();
System.out.println("Testing whether the following "
+ "string is a palindrome:");
System.out.println(" " + string);
System.out.println();
if (isPalindrome(string)) {
System.out.println("It IS a palindrome!");
} else {
System.out.println("It is NOT a palindrome!");
}
System.out.println();
}
}
Enjoy.
public boolean isPalindrom(String text) {
StringBuffer stringBuffer = new StringBuffer(text);
return stringBuffer.reverse().toString().equals(text);
}
I guess this is simple way to check palindrome
String strToRevrse = "MOM";
strToRevrse.equalsIgnoreCase(new StringBuilder(strToRevrse).reverse().toString());
I'm new to java and I'm taking up your question as a challenge to improve my knowledge as well so please forgive me if this does not answer your question well:
import java.util.ArrayList;
import java.util.List;
public class PalindromeRecursiveBoolean {
public static boolean isPalindrome(String str) {
str = str.toUpperCase();
char[] strChars = str.toCharArray();
List<Character> word = new ArrayList<>();
for (char c : strChars) {
word.add(c);
}
while (true) {
if ((word.size() == 1) || (word.size() == 0)) {
return true;
}
if (word.get(0) == word.get(word.size() - 1)) {
word.remove(0);
word.remove(word.size() - 1);
} else {
return false;
}
}
}
}
If the string is made of no letters or just one letter, it is a
palindrome.
Otherwise, compare the first and last letters of the string.
If the first and last letters differ, then the string is not a palindrome
Otherwise, the first and last letters are the same. Strip them from the string, and determine whether the string that remains is a palindrome. Take the answer for this smaller string and use it as the answer for the original string then repeat from 1.
The only string manipulation is changing the string to uppercase so that you can enter something like 'XScsX'
check this condition
String string="//some string...//"
check this...
if(string.equals((string.reverse())
{
it is palindrome
}
public static boolean istPalindrom(char[] word){
int i1 = 0;
int i2 = word.length - 1;
while (i2 > i1) {
if (word[i1] != word[i2]) {
return false;
}
++i1;
--i2;
}
return true;
}
import java.util.Scanner;
public class FindAllPalindromes {
static String longestPalindrome;
public String oldPalindrome="";
static int longest;
public void allSubstrings(String s){
for(int i=0;i<s.length();i++){
for(int j=1;j<=s.length()-i;j++){
String subString=s.substring(i, i+j);
palindrome(subString);
}
}
}
public void palindrome(String sub){
System.out.println("String to b checked is "+sub);
StringBuilder sb=new StringBuilder();
sb.append(sub); // append string to string builder
sb.reverse();
if(sub.equals(sb.toString())){ // palindrome condition
System.out.println("the given String :"+sub+" is a palindrome");
longestPalindrome(sub);
}
else{
System.out.println("the string "+sub+"iss not a palindrome");
}
}
public void longestPalindrome(String s){
if(s.length()>longest){
longest=s.length();
longestPalindrome=s;
}
else if (s.length()==longest){
oldPalindrome=longestPalindrome;
longestPalindrome=s;
}
}
public static void main(String[] args) {
FindAllPalindromes fp=new FindAllPalindromes();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String ::");
String s=sc.nextLine();
fp.allSubstrings(s);
sc.close();
if(fp.oldPalindrome.length()>0){
System.out.println(longestPalindrome+"and"+fp.oldPalindrome+":is the longest palindrome");
}
else{
System.out.println(longestPalindrome+":is the longest palindrome`````");
}}
}