Hi i am trying to write a palindrome method but am getting the wrong results
public static boolean isPalindrome(String input){
int b=input.length();
int []array=new int[b];
for(int i=0;i<array.length;i++){
array[i]=Integer.parseInt(input);}
for(int i=0;i<(array.length)/2;i++){
if(!(array[i]==array[array.length-1-i])){
return false;}
}
return true;
}
}
If you put the String into a StringBuilder you can use the .reverse() method. then just check if the 2 are equal.
StringBuilder input = new StringBuilder("helloolleh");
StringBuilder value = input.reverse();
if(value.toString().equals(input.toString()){
//process
}
You can go for the simpler method to check for palindrome.
Use the StringBuilder class and use the .reverse() method to reverse the string and then check for palindrome test.
StringBuilder value1= new StringBuilder("nitin");
StringBuilder value2 = input.reverse();
if(value1.toString().equals(value2.toString()){
System.out.println("This is a palindrome string ..");
}
Or you can go by this way also ..
public static boolean isPalindrome(String word) {
int left = 0;
int right = word.length() -1;
while (left < right) {
if (word.charAt(left) != word.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
Not sure why you are using Integer.Parse().
Try something like this (mostly following the logic from the question)
public static boolean isPalindrome(String input) {
char[] array = input.toCharArray();
for (int i = 0; i < (array.length) / 2; i++) {
if (!(array[i] == array[array.length - 1 - i])) {
return false;
}
}
return true;
}
You can use two "pointers" one starting from the beginning of the string and one from the end, and move them in opposite directions checking that characters are equals; as soon as you find a difference you know your string is not palindromic; conversely, if you don't find differences you know the string is palindromic:
public static boolean isPalindome(String input) {
char[] cs = input.toCharArray();
for (int i = 0, j = cs.length - 1; i < j; i++, j--) {
if (cs[i] != cs[j])
return false;
}
return true;
}
import java.util.Scanner;
public class Test_String {
private static boolean IsPalindrome(String s)
{
StringBuffer str1 = new StringBuffer(s);
StringBuffer str2 = str1.reverse();
if(s.equalsIgnoreCase(str2.toString()))
return true;
else
return false;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String to be checked as Palindrome ");
String in = scan.nextLine();
if(IsPalindrome(in))
System.out.println("\nEntered String is a Palindrome ");
else
System.out.println("\nEntered String is NOT a Palindrome ");
}
}
Related
import java.util.Scanner;
public class Pailindrome {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
System.out.println("Please enter a word");
String ori = sc1.nextLine();
isPailindrome(ori);
if (isPailindrome(ori))
System.out.println(ori + "is a Pailindrome");
else
System.out.println(ori + "is NOT a Pailindrome");
}
public static boolean isPailindrome(String ori) {
int i = 0;
int j = ori.length() - 1;
while (i < j) {
if (ori.charAt(i) != ori.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
}
The code works perfectly I'm just confused how I will get it to work irrespective of the case
inputted by the user. For example aBba is a palindrome but It says it's not in the code I've done. I
would like any help if possible thanks.
You can convert all of the letters to lowerCase before you start the processing.
You can write your own function or use toLowerCase() String function.
import java.util.Scanner;
public class Pailindrome {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
System.out.println("Please enter a word");
String ori = sc1.nextLine();
ori = ori.toLowerCase();
isPailindrome(ori);
if (isPailindrome(ori))
}
System.out.println(ori + "is a Pailindrome");
} else {
System.out.println(ori + "is NOT a Pailindrome");
}
}
public static boolean isPailindrome(String ori) {
int i = 0;
int j = ori.length() - 1;
while (i < j) {
if (ori.charAt(i) != ori.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
Take the input and call toUpper(); that way when you check to see if it is a palindrome, all of the characters are uppercase.
String ori = scr.nextLint();
if(isPalindrome(ori.toUpperCase()))
//do something
Convert all the cases to lowercase/uppercase before checking the palindrome
isPailindrome(ori.toLowerCase());
Zoom in from both ends and adjust the case as required.
public static boolean isPalindrome(String str) {
int len = str.length();
for (int i = 0; i < len >>1; i++) {
if (Character.toLowerCase(str.charAt(i)) !=
Character.toLowerCase(str.charAt(len - i - 1))) {
return false;
}
}
return true;
}
For example, the result of toNumber("3.2ac4.8rw2") would be 10 (=3.2+4.8+2).
My Code that I created is below. However it is failing at what I tend to do and I cannot come up with a solution.
public class toNumber {
public static int toNumber(String s) {
if (s == null || s.length() == 0) {
return 0;
}
char next = s.charAt(0);
if (Character.isDigit(next)) {
return Character.digit(next, 10) + toNumber(s.substring(1));
}
else
{
return toNumber(s.substring(1));
}
}
public static int to1Number(String input)
{
if(input ==null || input.length()==0)
return 0;
if(Character.isDigit(input.charAt(input.length()-1)))
return input.charAt(input.length()-1) +
toNumber(input.substring(0, input.length()-1));
else
return toNumber(input.substring(0, input.length()-1));
}
public static void main(String []args)
{
String input;
Scanner kb = new Scanner(System.in);
System.out.println("please enter some input");
input = kb.nextLine();
System.out.println(to1Number(input));
}
}
**I Tested it like this **
please enter some input
my input: t4343
result returned: 62
If you need it recursive:
public int toNumber(String str) {
char ch = str.charAt(0);
int count = Character.isDigit(ch) ? Character.getNumericValue(ch) : 0;
return str.length() > 1 ? count + toNumber(str.substring(1)) : count;
}
Or java 8 using streams without recursion:
public int toNumber(String str) {
return str.chars()
.mapToObj(i->(char)i)
.filter(Character::isDigit)
.mapToInt(Character::getNumericValue)
.sum();
}
Or with a standard loop without recursion:
public int toNumber(String str) {
int count = 0;
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(Character.isDigit(ch)) {
count += Character.getNumericValue(ch);
}
}
return count;
}
If you also want to count floating numbers, a solution using regular expressions would be the simpler one:
private double toNumber(String str) {
ArrayList<String> nums = new ArrayList<>();
Pattern pattern = Pattern.compile("\\d+(\\.\\d*)?"); // If you want to limit the decimal count to 1: "\\d{1}(\\.\\d{1})?"
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
nums.add(matcher.group());
}
return nums.stream().mapToDouble(Double::valueOf).sum();
}
This is a recursion program to test whether or not a sentence is a palindrome. It will run correctly if I write "bob" but not for "Madam I'm Adam" because of the caps and symbols. We are required to use a clean string method(?) to eliminate the spaces, symbols, and caps. This is what I have but I don't believe I've implemented it correctly. Could someone tell me how to improve/fix this? (Yes, I've looked all over the internet)
import java.util.Scanner;
public class Palindromes {
public static boolean isaPalindrome(String s) {
String cleanedString = clean(s);
if (s.length() == 0 || s.length() == 1)
return true;
if (s.charAt(0) == s.charAt(s.length() - 1))
return isaPalindrome(s.substring(1, s.length() - 1));
return false;
}
public static void main(String[] args) {
System.out.print("Enter a palindrome to test: ");
Scanner console = new Scanner(System.in);
String inStr = console.nextLine();
if (isaPalindrome(inStr)) {
System.out.printf("The input string, %s, is a palindrome.\n",
inStr);
reverseStr(inStr); // must be recursive!
System.out.println();
} else {
System.out.printf("The input string, %s, is not a palindrome.\n",
inStr);
}
}
private static String clean(String s) {
String cleaned = "";
return cleaned;
}
private static String reverseStr(String inStr) {
if ((null == inStr) || (inStr.length() <= 1)) {
return inStr;
}
return reverseStr(inStr.substring(1)) + inStr.charAt(0);
}
}
Your recursive method isaPalindrome is correct. If you want to further improve it, I would suggest you to avoid using subString to create parameters for your recursive call, this will create too many strings.
Instead, keep track of the positions of the characters in the original string that you are comparing:
public static boolean isaPalindrome(String s, int leftIndex, int rightIndex) {
if (leftIndex == rightIndex) return true;
if (s.charAt(leftIndex) == s.charAt(rightIndex))
return isaPalindrome(s, leftIndex + 1, rightIndex - 1);
return false;
}
You would invoke the method as: isaPalindrome(inStr, 0, inStr.length() - 1)
As for your clean method, you can use toLowerCase and Character.isLetter method to process the original string.
private static String clean(String s) {
String lowerCaseString = s.toLowerCase();
StringBuffer result = new StringBuffer();
for (int i = 0; i < lowerCaseString.length(); ++i) {
if (Character.isLetter(lowerCaseString.charAt(i))) {
result.append(lowerCaseString.charAt(i));
}
}
return result.toString();
}
Try this:
public static void main(final String[] args) {
final String unclean = "Madam I'm Adam";
final String clean = cleanString(unclean);
System.out.println("Clean string is: " + clean);
}
static private String cleanString(final String pTheString) {
final StringBuilder sb = new StringBuilder(pTheString.length());
for (final char c : pTheString.toCharArray()) {
switch (c) {
// ignore all those
case ' ':
case '\'':
case '.':
break;
// write the rest
default:
sb.append(c);
}
}
return sb.toString().toLowerCase();
}
I have a Java Assignment where I have to prompt for a line input, check if its a palindrome and then say if the palindrome is made of all text, all numbers, or mixed. I haven't added the part where I check what kind of palindrome it is yet, but I need help with the code to check if it's a palindrome. The code I posted below recognizes everything as a palindrome even if it isn't. This is basic Java so I'm limited to what I used below.
import java.util.Scanner;
public class Project4{
public static void main (String [] args)
{
String line = getInputLine();
while (!isEmptyLine (line))
{
if (isPalindrome (line))
System.out.println ("\"" + line + "\" is a palindrome.");
else
System.out.println ("\"" + line + "\" is not a palindrome");
line = getInputLine();
}
System.out.println ("End of program");
}
public static String getInputLine ( )
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a line of input: ");
String inputline = in.nextLine();
return inputline;
}
public static boolean isEmptyLine(String str)
{
boolean truefalse;
if(str.length()==0)
truefalse = true;
else
truefalse = false;
return truefalse;
}
public static boolean isPalindrome(String str)
{
int left = 0;
int right = str.length();
boolean okay = true;
char ch1; char ch2;
while(okay && left<right)
{
ch1 = str.charAt(left);
if(!Character.isDigit(ch1)||!Character.isLetter(ch1))
left++;
else
{
ch2 = str.charAt(right);
if(!Character.isDigit(ch2)||!Character.isLetter(ch2))
right--;
else
{
ch1 = Character.toUpperCase(ch1);
ch2 = Character.toUpperCase(ch2);
if(ch1==ch2)
{
left++;
right--;
}
else
okay = false;
}
}
}
return okay;
}
}
You need to do logical AND of the 2 checks instead of OR -
if(!Character.isDigit(ch1) && !Character.isLetter(ch1))
Use a method like the following:
boolean isPalindrome (String input) {
int strLength = input.length;
for (int i=0; i < input.length/2; ++i) {
if (input.charAt(i) != input.charAt(strLength-i)) {
return false;
}
}
return true;
}
A late answer although it might help some in the future. The method posted below doesn't use any of StringBuilder functions.
public boolean isPalindrome(String value) {
boolean isPalindrome = true;
for (int i = 0 , j = value.length() - 1 ; i < j ; i ++ , j --) {
if (value.charAt(i) != value.charAt(j)) {
isPalindrome = false;
}
}
return isPalindrome;
}
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`````");
}}
}