Why is this logic wrong for Integer palindrome - java

Refer below Java code for palindrome.
This is to check if the code logic is right or wrong
/* Please expalin why this logic is wrong*/
public class IntegerIsPalindrome {
public static boolean numPalindrome(int x){
String ParseNum = Integer.toString(x);
int lenPar = ParseNum.length();
for(int i = 0 ; i < ParseNum.length();i++){
if(ParseNum.charAt(0) != ParseNum.charAt(lenPar -1 -i)){
return false;
}
}
return true;
}
public static void main(String args[]){
boolean result = numPalindrome(323);
System.out.println(result);
}
}

It's because you always compare the first character. Specifically:
ParseNum.charAt(0)...
You should change this to:
ParseNum.charAt(i)...
Looking into 323, the first character, '3', and the last, '3', is compared. Then, the first '3' is compared with the '2', resulting in false.

You should iterate loop upto ParseNum.length()/2 is enough.
Ex: If value is 12321,
you should check
charAt[0] with charAt[4] means 1=1
charAt[1] with charAt[3] means 2=2
for(int i = 0 ; i < ParseNum.length()/2;i++){
if(ParseNum.charAt(i) != ParseNum.charAt(lenPar -1 -i)){
return false;
}
}

you should need to change ParseNum.charAt(0) in the for loop into ParseNum.charAt(i)
Here the code you can find palindrome easily:
package com.company;
import java.util.Scanner;
public class Palindrome
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Input: ");
String input = scanner.next();
System.out.println(isPalindrome(input) ? "palindrome" : "not a palindrome");
}
private static boolean isPalindrome(String input)
{
String temp = "";
for (int i = input.length() - 1; i >= 0; i--)
{
temp += input.charAt(i);
}
return input.equalsIgnoreCase(temp);
}
}

Related

I am trying to check for Anagram

Why the code is showing me the error for missing return statement?
What I am trying to do is check the length of the string followed by its content and compare both of them.
import java.util.Scanner;
public class Solution {
static boolean isAnagram(String a, String b) {
char[] arr1 = a.toLowerCase().toCharArray();
char[] arr2 = b.toLowerCase().toCharArray();
java.util.Arrays.sort(arr1);
java.util.Arrays.sort(arr2);
if (arr1.length != arr2.length) {
if (!arr1.equals(arr2)) {
System.out.println("Not Anagrams");
}
return false;
} else if (arr1.equals(arr2)) {
System.out.println("Anagrams");
return true;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String a = scan.next();
String b = scan.next();
scan.close();
boolean ret = isAnagram(a, b);
System.out.println((ret) ? "Anagrams" : "Not Anagrams");
}
}
PRIMARY QUESTION
You need to have a "return" outside if statements.
else if(arr1.equals(arr2))
{
System.out.println("Anagrams");
return true;
}
return false; //add this here. I tested, error goes after this.
}
Tested here - https://onlinegdb.com/S188-FdGL
EXTRA
Your Anagram logic is wrong.
The correct logic should be like this (follow comments to understand).
import java.util.Scanner;
import java.util.Arrays;
public class Solution {
static boolean isAnagram(String a, String b)
{
char[] arr1 = a.toLowerCase().toCharArray();
char[] arr2 = b.toLowerCase().toCharArray();
int n1 = arr1.length;
int n2 = arr2.length;
// If length is different, then they cannot be Anagram
if (n1 != n2) return false;
// Sort the Character Arrays
Arrays.sort(arr1);
Arrays.sort(arr2);
// Compare each characters of sorted Character Arrays,
// if any character mismatches, it is not an Anagram
for (int i = 0; i < n1; i++)
if (arr1[i] != arr2[i])
return false;
// If all characters of both character Arrays are same,
// only then, the String are Anagrams, so return true
return true;
// Also, remove the print statements from this method,
// as you are already printing in the main method,
// so it creates duplicate prints
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String a = scan.next();
String b = scan.next();
scan.close();
boolean ret = isAnagram(a, b);
System.out.println( (ret) ? "Anagrams" : "Not Anagrams" );
}
}
Tested here - https://onlinegdb.com/rJe-OEtuGL

Problem with Java code that will print TRUE when a word has no vowels in an IF statement

I am trying to write a code the will print TRUE when i enter a word with no vowels and will print FALSE if I enter a word with vowels. I am having trouble when it comes to writing the string. I give one of the strings the value that holds all the values.
String A = "aeiou";
The other 2 strings hold the rest of the alphabet.
When I type in a word that has vocals it prints FALSE however when I type in a word with no vowels it prints FALSE.
I wanna know if there is a way to make the program read the values of the string as separate entities and not as a whole line.
package lab3;
import java.util.Scanner;
public class Lab3 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String input = reader.next();
/* A and B, but not C */
String A = "bcdfghjklm";
String B = "npqrstvwxyz";
String C = "aeiou";
if (input.contains(A) && input.contains(B) || input.contains(C)) {
System.out.println("TRUE");
} else {
System.out.println("FALSE");
}
}
}
You can do it with a short function
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String input = reader.next();
System.out.println(chk(input));
}
static public boolean chk(String s) {
for (int i = 0; i < s.length(); i++) {
if ("aeiou".indexOf(s.charAt(i)) != -1) {
return false;
}
}
return true;
}
}
This is a working correct for your purpose:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String input = reader.next();
String C = "aeiou";
for (int i = 0; i < input.length(); i++) {
char inputA = input.charAt(i);
for (int j = 0; j < C.length(); j++) {
char c = C.charAt(j);
if (inputA == c) {
System.out.println("TRUE");
return;
}
}
}
System.out.println("FALSE");
}
The key point is to use the method charAt(int index); so you can check each char in the string.
You can choose to use any of the below two methods, containsVowel and containsVowel1 as both of them do the same thing:
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a text: ");
String input = reader.nextLine();
String[] vowels = { "a", "e", "i", "o", "u" };
System.out.println(!containsVowel(input, vowels));
System.out.println(!containsVowel1(input, vowels));
}
public static boolean containsVowel(String input, String[] vowels) {
return Arrays.stream(vowels).parallel().anyMatch(input::contains);
}
public static boolean containsVowel1(String input, String[] vowels) {
for (int i = 0; i < vowels.length; i++) {
if (input.contains(vowels[i])) {
return true;
}
}
return false;
}
}

Java Beginner, comparing strings in nested for loop

Here is the problem statement: Write a function that compares 2 strings to return true or false depending on if both strings contain the same letters. Order doesn't matter.
I do not know how to properly compare the character arrays in my nested for loop. I wish I could be more specific with what my issue is, but I'm a really new learner and can't see why this isn't working. I do believe it's not doing what I would like in the nested for loops. Thanks in advance!
import java.util.Scanner;
public class PracticeProblems {
public static boolean stringCompare(String word1, String word2) {
char[] word1b = new char[word1.length()];
char[] word2b = new char[word2.length()];
boolean compareBool = false;
for(int i = 0; i < word1.length(); i++) {
word1b[i] = word1.charAt(i);
word2b[i] = word2.charAt(i);
}
for(int i = 0; i < word1.length(); i++) {
for(int j = 0; j < word2.length(); j++) {
if(word1b[i] == word2b[j]) {
compareBool = true;
break;
} else {
compareBool = false;
break;
}
}
}
return compareBool;
}
public static void main(String []args) {
Scanner scan = new Scanner(System.in);
System.out.println("Word 1?");
String word1 = scan.nextLine();
System.out.println("Word 2?");
String word2 = scan.nextLine();
if(PracticeProblems.stringCompare(word1, word2) == true) {
System.out.println("Same Letters!");
} else {
System.out.println("Different Letters...");
}
}
The code below will do the job. This is essentially an expansion of Frank's comment above. We convert the two strings to two sets and then compare.
import java.util.*;
public class SameChars {
// Logic to convert the string to a set
public static Set<Character> stringToCharSet(String str) {
Set<Character> charSet = new HashSet<Character>();
char arrayChar[] = str.toCharArray();
for (char aChar : arrayChar) {
charSet.add(aChar);
}
return charSet;
}
// Compares the two sets
public static boolean hasSameChars(String str1, String str2) {
return stringToCharSet(str1).equals(stringToCharSet(str2));
}
public static void main(String args[]){
// Should return true
System.out.println(hasSameChars("hello", "olleh"));
// Should returns false
System.out.println(hasSameChars("hellox", "olleh"));
}
}
I sorted arrays before comparing.
//import statement for Arrays class
import java.util.Arrays;
import java.util.Scanner;
public class PracticeProblems {
public static boolean stringCompare(String word1, String word2) {
char[] word1b = new char[word1.length()];
char[] word2b = new char[word2.length()];
boolean compareBool = true;
for(int i = 0; i < word1.length(); i++) {
word1b[i] = word1.charAt(i);
}
//sort the new char array
Arrays.sort(word1b);
// added a second loop to for the second world
for(int i = 0; i < word2.length(); i++) {
word2b[i] = word2.charAt(i);
}
Arrays.sort(word2b);
for(int i = 0; i < word1.length(); i++) {
//removed second for loop.
// for(int j = 0; j < word2.length(); j++) {
// if the two strings have different length, then they are different
if((word1.length()!=word2.length())){
compareBool = false;
break;
}
//changed to not equal
if( (word1b[i] != word2b[i]) ) {
compareBool = false;
break;
}
//removed else statment
// else {
// compareBool = false;
// break;
//
// }
}
return compareBool;
}
public static void main(String []args) {
Scanner scan = new Scanner(System.in);
System.out.println("Word 1?");
String word1 = scan.nextLine();
System.out.println("Word 2?");
String word2 = scan.nextLine();
if(PracticeProblems.stringCompare(word1, word2) == true) {
System.out.println("Same Letters!");
} else {
System.out.println("Different Letters...");
}
//resource leak. use close() method.
scan.close();
}
}
Allow me to rename your boolean variable to letterFound (or maybe even letterFoundInWord2) because this is what you are checking in your double loop. Explanatory naming makes it easier to keep the thoughts clear.
Since you are checking one letter from word1 at a time, you can move the declaration of letterFound inside the outer for loop and initialize it to false here since each time you take a new letter from word1 you haven’t found it in word2 yet. In your if statement inside the for loops, it is correct to break in the case the letters are the same and you set letterFound to true. In the opposite case, don’t break, just go on to check the next letter. In fact you can delete the else part completely.
After the inner for loop, if letterFound is still not true, we know that the letter from word1 is not in word2. So stringCompare() should return false:
if (! letterFound) {
return false;
}
With this change, after the outer for loop we know that all letters from word1 were found in word2, so you can type return true; here.
Except:
You seem to be assuming the strings have the same length. If they have not, you program will not work correctly.
As Andy Turner said, you should also check that all the letters in word2 are in word1; it doesn’t follow from the letters from word1 being in word2.
Should only letters be considered? Should you ignore spaces, digits, punctuation, …?
Hope you will be able to figure it out. Feel free to follow up in comments or ask a new question.

String index out of range in jva

A string is a palindrome if it is spelled the same way backward and
forward.
Examples of palindromes include “Radar” and “Dammit, I’m mad!”.
Write a java program, PalindromeTester, that asks the user to enter a
word or sentence and then checks whether the entered string is a
palindrome or not.
Spaces, nonalphabetics (.,!:?-()\";), and case within the string have
to be ignored e.g., "Drab as a fool, aloof as a bard." is a
palindrome.
Your implementation should define and use the method isPalindrome to
test if a certain string is a palindrome. The signature of the
isPalindrome method is as follows:
boolean isPalindrome(String)
Following is a sample run of the program. The user’s input is shown in bold.
java PalindromeTester
Introduction to Computer Programming (CMPS 200)
Spring 2015-16 2 of 3
Enter a string: I love CMPS 200
The string "I love CMPS 200" is NOT a palindrome.
This is the code I made, it keeps giving me an error.
I would like to know what my error is and whether there's a faster easier way of writing this code
import java.util.Scanner;
public class PalindromeTester {
public static void main (String args []) {
Scanner console = new Scanner(System.in);
System.out.println("Enter a string: ");
String palindrome = console.next();
if (isPalindrome (palindrome)) {
System.out.print("The string \""+palindrome+" is a palindrome.");
} else {
System.out.print("The string \""+palindrome+" is NOT a palindrome.");
}
}
public static boolean isPalindrome (String palindrome) {
int constant = 1;
for (int i = 0 ; i <= (palindrome.length()-1) ; i++) {
for (int z= (palindrome.length()-1);i >= 0; i--) {
if (palindrome.charAt(i) <'#'||'Z'<palindrome.charAt(i)&&palindrome.charAt(i)<'`'||'['<palindrome.charAt(i)&&palindrome.charAt(i)<'{') {
i=i+1;
}
if (palindrome.charAt(z)<'#'||'Z'<palindrome.charAt(z)&&palindrome.charAt(z)<'`'||'['<palindrome.charAt(z)&&palindrome.charAt(z)<'{') {
z=z+1;
}
if (palindrome.charAt(i)==(palindrome.charAt(z))) {
constant = constant * 1;
} else {
constant = constant * 0;
}
}
}
if (constant == 0 ) {
return false;
} else {
return true;
}
}
}
One approach would be to strip the non alpha characters out of the string. Then check if the string is the same as itself reversed (while upper case):
public static boolean isPalindrome(String palindrome) {
StringBuilder sanitisedString = new StringBuilder();
for(char c : palindrome.toCharArray()) {
if(Character.isLetter(c)) {
sanitisedString.append(c);
}
}
return sanitisedString.toString().toUpperCase().equals(sanitisedString.reverse().toString().toUpperCase());
}
Index out of range is caused by palindrome.charAt(z)) after z = z + 1;
Keep simple :
public static boolean isPalindrome(String palindrome)
{
palindrome = palindrome.replaceAll("\\W", ""); // remove all non word character
palindrome = palindrome.toLowerCase();
int size = palindrome.length();
int halfSize = size / 2;
for (int i = 0; i < halfSize; i++)
{
if(palindrome.charAt(i) != palindrome.charAt(size - i - 1))
return false;
}
return true;
}
Why not just make a new String and save the reversed source(String) in it.
public static boolean readstring(String s)
{
String b = "";
for (int i= s.length() -1; i >=0 ;i--)
{
b = b + s.charAt(i);
}
System.out.print(b +" and "+ s +" ");
return b == s || b.Equals(s);
}
EDIT: Hopefully this meets the requirements, by the way dont use the word "ignore" but "allow"
public boolean isPalindrome(String word) {
int backward = word.length() - 1;
for (int x = 0; x < word.length(); x++) {
if (word.charAt(x)!= word.charAt(backward--)) {
return false;
}
}
return true;
}

Searching for specific character in string with static method

I have to make a program that counts the number of the letter B in a string. I got that part already, but it also requires me to use a static method that returns true or false based on if the string has any Bs in it and i really don't see how to fit that part in.
import java.util.Scanner;
public class CountB {
// write the static method “isThisB” here
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a string: ");
String w = keyboard.nextLine();
int count=0;
for (int i=0; i<w.length(); i++)
{
if (w.charAt(i)=='B'||w.charAt(i)=='b')
{
count++;
}
}
System.out.println("Number of B and b: "+ count);
}
}
private static boolean hasAnyB(String str) {
return str.contains("B") || str.contains("b");
}
Something like this:
static boolean check(String str){
if(str.indexOf('B')>0 || str.indexOf('b')>0 )
return true;
else
return false;
}
Use the built-in matches() method, which uses regex:
private static boolean hasB(String str) {
return str.matches(".*[bB].*");
}
Using regex is a near way to handle mixed case issues.
Just Deploy all coding inside a static method that's it
public static void main(String[] args)
{
methodOne("Pass string over here");
}
public static boolean methodOne(String s)
{
return s.contains("B");
}
To get the count of b or B you can do
int bCount = w.replaceAll("[^Bb]", "").length();
If you have to use a hasB method you could do it like this, though its pretty inefficient and longer than it needs to be
int count = 0;
for(String ch: w.split("")) // one character at a time.
if(hasB(ch))
count++;
private static boolean hasAnyB(String str) {
return str.toLowerCase().contains("b");
}
The easiest i could think.
static boolean isThisB(String s, int count) {
for(int i=0; i<s.lenght(); i++) {
char c = s.charAt(i);
if(c == 'b' || c == 'B')
count ++;
}
return count > 0;
}

Categories

Resources