This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
Hi I'm trying to build a palindrome but it seem to be not working, please could you help. I'm expected to catch true on dad and false on other things
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter Your User Name");
String userInput =input.nextLine();
System.out.println(abcDEF(userInput));
}
static boolean abcDEF(String userInput) {
StringBuilder s1 = filter(userInput);
StringBuilder s2 = reverse(userInput);
return s1.toString() == s2.toString();
}
static StringBuilder filter(String userInput) {
StringBuilder sb = new StringBuilder();
char[] inputData = userInput.toCharArray();
for (int i = 0; i < userInput.length(); i++) {
if (userInput.matches("[a-zA-Z0-9]+")) {
sb.append(inputData[i]);
}
}
return sb;
}
static StringBuilder reverse(String userInput) {
StringBuilder sb = filter(userInput);
sb.reverse();
return sb;
}
change your abcDEF() to this(last line):
static boolean abcDEF(String userInput) {
StringBuilder s1 = filter(userInput);
StringBuilder s2 = reverse(userInput);
return s1.toString().equals(s2.toString());
}
You are comparing the references of two strings in your code, which is not same in your case. Rather, you should compare the content of the strings. And this is how String contents are compared.
Related
I tried to write a program to check whether a number is a palindrome or not in Java. I tried to convert int to String, and using built-in methods, wrote this logic. But I don't know why I am getting incorrect output for the given input.
class Main {
public static void main(String[] args) {
int x=1213;
StringBuilder s= new StringBuilder();
s.append(x);
StringBuilder s2=new StringBuilder();
s2=s.reverse();
if((s.toString()).equals(s2.toString()))
{
System.out.println(x+" is a palindrome number");
}
else{
System.out.println(x+"is not a palindrome number");
}
}
s2=s.reverse();
Here the StringBuilder class is not immutable , reverse operation will reverse the content of the original the StringBuilder s, you should construct a new StringBuilder here :
public class Main {
public static void main(String[] args) {
int x=1213;
StringBuilder s= new StringBuilder();
s.append(x);
StringBuilder s2=new StringBuilder();
s2=new StringBuilder(s).reverse();
if((s.toString()).equals(s2.toString()))
{
System.out.println(x+" is a palindrome number");
}
else{
System.out.println(x+"is not a palindrome number");
}
}
}
You call s.reverse(), which reverses s in place; and you assign it to s2, so s and s2 are the same object.
You don't need two StringBuilders at all, since you only need to make one modification.
StringBuilder sb = new StringBuilder();
sb.append(x);
sb.reverse();
if (sb.toString().equals(String.valueOf(x))) {
// the number is a palindrome
}
This question already has answers here:
What is the best way to tell if a character is a letter or number in Java without using regexes?
(9 answers)
Closed 3 years ago.
I need to iterate through the String userInput and find if the char is a letter or digit, if it is then I need to append that char to the String endProduct.
public static String converter(String userInput) {
String endProduct = "";
char c = userInput.charAt(0);
Stack<Character> stack = new Stack<Character>();
int len = userInput.length();
//iterates through the word to find symbols and letters, if letter or digit it appends to endProduct, if symbol it pushes onto stack
for (int i = c; i < len; i++) {
if (Character.isLetter(userInput.charAt(i))) {
endProduct = endProduct + c;
System.out.println(c);
}//end if
else if(Character.isDigit(userInput.charAt(i))){
endProduct = endProduct + c;
System.out.println(c);
}
Here are some ways to accomplish this.
Method 1 - traditional Java.
private static String converter(String userInput) {
final StringBuilder endProduct = new StringBuilder();
for(char ch : userInput.toCharArray()) {
if(Character.isLetterOrDigit(ch)) endProduct.append(ch);
}
return endProduct.toString();
}
Method 2 - Streams.
private static String converter(String userInput) {
int[] chars = userInput.codePoints().filter(Character::isLetterOrDigit).toArray();
return new String(chars, 0, chars.length);*/
}
or
private static String converter(String userInput) {
return userInput.codePoints().filter(Character::isLetterOrDigit).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
So when I'm running this code with any word, it is always returning false. The first String accepts the word, and then it's changed to lower case. Then I'm building a new String out of it to compare it to another string that is appended as the reverse of the original word. Am I not seeing something, or can you tell me what's wrong with it?
public class Palindromes
{
public static void main(String[] args)
{
int count = Integer.parseInt(args[0]);
for(int i = 1; i <= count; i++)
{
System.out.print(isPalindrome(args[i]) + " ");
}
}
public static boolean isPalindrome(String s)
{
String str = s.toLowerCase();
StringBuilder orig_str = new StringBuilder(str);
StringBuilder revStr = new StringBuilder();
for (int i = str.length()-1; i >= 0; i--)
{
revStr.append(orig_str.charAt(i));
}
boolean isPal = (revStr == orig_str);
return isPal;
}
}
Comparing two distinct StringBuilder instances with == would always give you false, regardless of their content, since they are not the same instance.
Try revStr.toString().equals(str)
It seems that StringBuilder doesn't override Object's equals, so you have to perform the equals on the Strings that result from the StringBuilders.
BTW, StringBuilder has a reverse method, so you can re-write your method in a single line :
public static boolean isPalindrome(String s) {
return new StringBuilder(s.toLowerCase()).reverse().toString().equals(s.toLowerCase());
}
This question already has answers here:
How to check if a String contains another String in a case insensitive manner in Java?
(19 answers)
Closed 8 years ago.
I wrote a code to find a substring within a string in java but i want to know is there a short way to do this or is there a inbuilt function to do this.
Here's the code :
import java.util.*;
class substr
{
public static void main (String args [])
{
String str1 = new String();
String str2 = new String();
String str3 = new String();
int check=1,k;
Scanner obj= new Scanner (System.in);
System.out.println("Enter a string");
str1=obj.nextLine();
System.out.println("Enter Sub String");
str2=obj.nextLine();
int len=str1.length();
System.out.println(check);
for( int c = 0 ; c < len&&check!=0 ; c++ )
{
for( int i = 1 ; i <= len - c&& check!=0 ; i++ )
{
str3 = str1.substring(c, c+i);
if (str2.equals(str3))
{
check=0;
}
}
}
System.out.println(check);
if (check==0)
{
System.out.println("Sub String");
}
else if ( check==1)
{
System.out.println("No");
}
}
}
If you are asking for a way to do what your code does (check if a string is substring of another string), you can use String#contains:
if(str1.contains(str2)) {
System.out.println("Sub String");
} else {
System.out.println("No");
}
You can also use String#indexOf:
if(str1.indexOf(str2)>=0) {
System.out.println("Sub String");
} else {
System.out.println("No");
}
Main Class (required)
import java.util.*;
public class FindingPalindrome {
private String inputString;
private Stack<Character> stack = new Stack<Character>();
public FindingPalindrome(String str)
{
inputString = str;
fillStack();
}
public void fillStack()
{
for(int i = 0; i < inputString.length(); i++)
{
stack.push(inputString.charAt(i));
}
}
public String reverseString()
{
String result = new String();
while(!stack.isEmpty())
{
result = result.concat(Character.toString(stack.pop()));
}
return result;
}
public boolean isPalindrome()
{
if(inputString.equalsIgnoreCase(reverseString()))
return true;
else return false;
}
}
Tester Class (required)
import java.util.*;
public class TestPalindrome
{
private static Scanner s;
public static void main(String args[])
{
s = new Scanner(System.in);
System.out.println("Enter the string");
// Read the data
String st1=s.nextLine();
// Create StringBuffer obj for st1
StringBuffer sb=new StringBuffer(st1);
// Reverse the letters
sb.reverse();
st1 = st1.toLowerCase().replaceAll("[^a-z]","");
// Check & Print if palindrome
if(st1.equals(sb.toString()))
System.out.println("Palindrome String");
}
}
Whenever I add "Stop! pots" the code terminates itself and doesn't print the output. I also added the replaceAll(), but it didn't work either. Simple palindrome works "ada", "Kayak", but palindrome with spaces and characters is not working
You are doing it in the wrong order:
// Read the data
String st1=s.nextLine();
// Create StringBuffer obj for st1
StringBuffer sb=new StringBuffer(st1);
// Reverse the letters
sb.reverse();
st1 = st1.toLowerCase().replaceAll("[^a-z]",""); // <<<<<<< too late.
// You created sb with the original
// including punctuation
// Check & Print if palindrome
if(st1.equals(sb.toString()))
System.out.println("Palindrome String");
Replace with
// Read the data
String st1=s.nextLine();
st1 = st1.toLowerCase().replaceAll("[^a-z]",""); // <<<< moved this
// Create StringBuffer obj for st1
StringBuffer sb=new StringBuffer(st1); // <<<< now this is a copy without punctuation
// Reverse the letters
sb.reverse();
// Check & Print if palindrome
if(st1.equals(sb.toString()))
System.out.println("Palindrome String");