Palindrome for Integers and Strings Java - java

I'm trying to create Palindrome app for Integers and Strings in Java, I'm having an issue with my if statement, it outputs incorrect/repeating True and False statements:
import java.util.Scanner;
import java.io.*;
public class Palindrome {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.println("Enter characters to check for Palindrome: ");
if ( user_input.hasNextInt() ){
String intToString = String.valueOf(user_input.nextInt()).toString();
String reversedInt = new StringBuffer(intToString).reverse().toString();
for (int i = 0; i<intToString.length(); i++) {
if (intToString.charAt(i) != reversedInt.charAt(i)) {
System.out.println("False");
}
else {
System.out.println("True");
}
}
}
else if ( user_input.hasNextLine() ) {
String user_string = user_input.nextLine().replaceAll(" ", "").toLowerCase();
StringBuilder user_mutable_string = new StringBuilder(user_string);
user_mutable_string.reverse();
if (user_string.equals(user_mutable_string.toString())) {
System.out.println("True");
}
else {
System.out.println("False");
}
}
else {
System.out.println("Bonkers!");
}
}
}

Your issue is with the for loop, which you don't need. You have already reversed the numbers and converted both the original and reversed numbers to a String. All you need to do then is to compare them. Change the for loop to a simple if:
if (intToString.equals(reversedInt)) {
System.out.println("True");
}
else {
System.out.println("False");
}

Since you are using a loop to check the whole string, you don't want to output True immediately, since you don't know yet at that point. It could be, that the next char won't pass the condition.
You should use a boolean variable instead, like this
boolean isPalindrome = true; // let's assume it will be ok
for (int i = 0; i<intToString.length(); i++) {
if (intToString.charAt(i) != reversedInt.charAt(i)) {
isPalindrome = false;
}
}
System.out.println(isPalindrome);

Related

Anagram Checking Logical Error - Cant seem to find the error

public class AnagramUnoptimized {
public static void main(String[] args) {
String a = "good";
String b = "ogod";
boolean isAnagram = false;
String c = a.toLowerCase();
String d = b.toLowerCase();
if(c.length()==d.length()) {
boolean [] Visited = new boolean[a.length()];
for (int i = 0; i < c.length(); i++) {
isAnagram = false;
for (int j = 0; j < d.length(); j++) {
if (c.charAt(i) == d.charAt(j) && Visited[j]==false) {
isAnagram = true;
Visited[j] = true;
}
}
if (isAnagram == false) {
break;
}
}
}
if(isAnagram==true){
System.out.println("The given Strings are Anagrams");
}
else{
System.out.println("The given Strings are not Anagrams");
}
}
}
I used a Visited boolean array to check for repeated items but its now showing "Not anagram" for all inputs....
Can you tell me why its showing "Not anagram" if the strings have repeating elements??
The problem with your code is you are continuing with the loop even when visited[j] is changed to true whereas you need to break the inner loop at this point. Do it as follows:
for (int j = 0; j < d.length(); j++) {
if (c.charAt(i) == d.charAt(j) && visited[j] == false) {
isAnagram = true;
visited[j] = true;
break;
}
}
The output after this change:
The given Strings are Anagrams
A better way to do it would be as follows:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String a = "good";
String b = "ogod";
char[] first = a.toLowerCase().toCharArray();
char[] second = b.toLowerCase().toCharArray();
Arrays.sort(first);
Arrays.sort(second);
boolean isAnagram = Arrays.equals(first, second);
if (isAnagram == true) {
System.out.println("The given Strings are Anagrams");
} else {
System.out.println("The given Strings are not Anagrams");
}
}
}
Output:
The given Strings are Anagrams
In your code you should break the inner for loop when the
condition "if (c.charAt(i) == d.charAt(j) && Visited[j]==false)"
has been meet. Because it is still looping through the second stiring and if it will meet the same char one angain it will change the value of Visited[] to true two times, leading to an error. It this example this is the case witch char 'o'. Adding " break; " at the end of the if statement should fix the problem.

Isogram- a word without repeated letters

I want to develop a java code to detect a repeated letter in word and print the desired result but mine keeps iterating and i have no idea on how to get about it. Here is the code:
import java.util.*;
public class Isogram {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter the name: ");
String car = input.nextLine().toLowerCase();
char[] jhd = car.toCharArray();
Arrays.sort(jhd);
for(int ch = 0; ch < jhd.length; ch++){
try {
if (jhd[ch] == jhd[ch + 1]) {// || jhd[ch] == jhd[ch]){
System.out.print("THis is an Isogram");
} else {
System.out.println("Ripu from here");
}
} catch(ArrayIndexOutOfBoundsException ae) {
System.out.println(ae);
}
}
}
}
If u have an adjustment or a better code it will be helpful.
private static String isIsogram(String s){
String[] ary = s.split("");
Set<String> mySet = new HashSet<String>(Arrays.asList(ary));
if(s.length() == mySet.size()){
return "Yes!";
}else{
return "NO";
}
}
Create an array from the string.
Convert array to a List and then create a Set from that List. Set
keeps only unique values.
If set size equals the initial string length then it is an
isogram. If set is smaller than initial string then there were
duplicate characters.
public static boolean isIsogram(String str) {
boolean status = true;
char [] array = str.toCharArray();
Character[] charObjectArray = ArrayUtils.toObject(array);
Map<Character,Integer> map = new HashMap<>();
for (Character i : charObjectArray){
Integer value = 1;
if (map.containsKey(i)){
Integer val = map.get(i);
map.put(i,val+1);
}
else map.put(i,value);
}
for (Integer integer: map.values()){
if (integer>1){
status= false;
break;
}
else status = true;
}
return status;
}
}

Trouble checking if a string is a palindrome

I am a beginner learning Java and have been asked to check if a given string is a palindrome.
Here is what I have so far:
int namel = name.length();
for (int i =0; i<=namel; i++)
{
char letter = name.charAt(i);
char namerev = name.charAt(namel-i);
String letterS =txtNamePali.getText();
if(letter==namerev)
{
txtNamePali.setText("Palindrone");
}
else
{
txtNamePali.setText( "Not a Palindrone");
}
}
Unfortunately my textbox isn't showing any output. I have searched for how to fix the issue but couldn't find an answer relating to what I have learnt in class.
What did I do wrong, and how can I correct it?
I think the easiest test is to use the StringBuilder.reverse() to construct the reverse of the input. Also, the word is usually spelled palindrome.
StringBuilder sb = new StringBuilder(name);
sb.reverse();
String msg = (sb.toString().equals(name)) ? "Palindrome" : "Not a Palindrome";
txtNamePali.setText(msg);
You can do it using a StringBuilder
Use the reverse function in that.
Example:
public static void main(String args[]){
String str = "1234";
String str1 = "1234321";
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(str);
if(stringBuilder.reverse().toString().equals(str)){
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
stringBuilder = new StringBuilder();
stringBuilder.append(str1);
if(stringBuilder.reverse().toString().equals(str1)){
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
}
Output:
Not Palindrome
Palindrome
Int short you can just do
new StringBuilder().append(yourString).reverse().toString().equals(yourString)
This return a boolean true if the string is palindrome else false.
Your code is on the right track, but as some people have said, there are a few errors you need to account for, which should appear as compiler issues.
int namel = name.length();
boolean isPalindrome = true;
//add a tracking value, it's a palindrome unless we prove it otherwise
for (int i =0; i< namel/2; i++)
//change from <= to < because arrays are 0-index, we also only have to check halfway so we can use namel/2
{
char letter = name.charAt(i);
char namerev = name.charAt(namel-i);
//String letterS =txtNamePali.getText(); <-- not sure what this was for, possibly a debug statement
if(letter!=namerev)
{
isPalindrome = false; //we have found a non-matching value, it'll stay false, and we'll output correctly
}
}
//then we set the text once. Keeping the text inside would have returned an erroneous "abbc" is a palindrome.
if(isPalindrome) {
txtNamePali.setText("Palindrone");
}
else {
txtNamePali.setText( "Not a Palindrone");
}
1.The result of the method should be given when the whole string got checked. So first put
if(letter==namerev)
{
txtNamePali.setText("Palindrone");
}
else
{
txtNamePali.setText( "Not a Palindrone");
}
outside the loop (and change the condition - like in my proposal below).
you can break the loop when the first mismatch of two chars occured.
2.Instead of char namerev = name.charAt(namel-i); you have reduce the position one more.
So use: char namerev = name.charAt(namel-1-i);
try something like this:
String s = "stringtotest";
boolean result = true;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != s.charAt(s.length()-1-i)) {
result = false;
break;
}
}
if (result)
System.out.println("Palindrom");
else
System.out.println("Not palindrom");
Same general idea as the others, but I think that this is cleaner and easier to read. Just a thought - everyone has their own style. :) If you're a beginner, I highly suggest getting into the habit of moving redundant logic to its own method. It's cleaner and may prove to be much more useful later.
public class Main {
public static void main( String args[] ) {
for ( String string : args ) {
if ( isPalendrome( string ) {
System.out.println("Palindrome");
} else {
System.out.println("Not a Palindrome");
}
}
}
private static boolean isPalindrome( String string ) {
return string.equals( reverse( string ) );
}
private static String reverse( String original ) {
return new StringBuilder(original).reverse().toString();
}
}
String name="pop"; // string to check if it palindrome or not
String revName="";
int namel = name.length();
for (int i =1; i<=namel; i++)
{
char namerev = name.charAt(namel-i);
revName += namerev;
}
if(name.equals(revName))
{
System.out.println("Palindrome");
}
else
{
System.out.println( "Not a Palindrome");
}

Iterating over a String to check for a number and printing out the String value if it doesn't have a number

I have set up my function for checking for a number in a String, and printing out that String if it has no numbers, and putting up an error message if it does. Here is my code:
public class NumberFunction
{
public boolean containsNbr(String str)
{
boolean containsNbr = false;
if(str != null && !str.isEmpty())
{
for(char c : str.toCharArray())
{
if(containsNbr = Character.isDigit(c))
{
System.out.println("Can't contain numbers in the word.");
break;
}
else
{
System.out.println(str);
}
}
}
return containsNbr;
}
}
import com.imports.validationexample.function.NumberFunction;
public class Main
{
public static void main(String[] args)
{
NumberFunction nf = new NumberFunction();
System.out.println(nf.containsNbr("bill4"));
}
}
I am trying to get it to print out the result to the console, but the result keeps printing multiple times and prints the boolean value, which I do not want, something like this:
bill4
bill4
bill4
bill4
Can't contain numbers in the word.
true
Why is this happening? I've tried casting but that hasn't worked out either. Any help would be much appreciated.
Well you're assingning the value to containsNbr.
if(containsNbr = Character.isDigit(c))
change that line for:
if(Character.isDigit(c)) { //will evaluate if 'c' is a number
containsNbr = true;
break;
}
Also don't have an else, put this after the for-each loop:
for(char c : str.toCharArray())
if(Character.isDigit(c)) { //will evaluate if 'c' is a number
containsNbr = true;
break;
}
}
if(containsNbr) {
System.out.println("Can't contain numbers");
}
else {
System.out.println(str);
}
So it will print only once the str word instead of n times.
You were printing it many times because your else was inside the for-loop. Taking it out, will solve the issue.
Also convert the function from boolean to void so you won't print that true or false at the end.

Java way to check if a string is palindrome [duplicate]

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

Categories