Checking Palindromes using an array - java

The object is to take a phrase entered by the user and tell them whether it is a palindrome or not. It must have an array and a method. I am having trouble with my array and the return result for my method. I have edited it some but I am still having trouble with the boolean part. No matter what I enter I am getting false. I would also like to make sure that if there was any spaces entered that they would be removed. I have tried the replaceAll but could not get that to work. Thank you for the help.
import java.util.Scanner;
public class palindrome {
public palindrome() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
int another=1;
boolean results;
System.out.println("Please enter a phrase to be checked:");
String input = keyboard.next();
if (checkpalindrome(input))
System.out.println("Yes, the phrase is a palindrome");
else
System.out.println("No, the phrase is not a palindrome");
System.out.println("Would you like to try another one? \"1 or 0\"");
another = keyboard.nextInt();
}
public static boolean checkpalindrome(String input){
char array2 = 0;
char[] array1 = input.toCharArray();
StringBuilder sb = new StringBuilder(input.length());
for(int i=0; i<array1.length/2; i++)
{
array2 = array1[i];
array1[i]=array1[array1.length-1-i];
array1[array1.length-1-i]=array2;
}
System.out.println(input);
System.out.println(array1);
System.out.println(test.equals(array1));
return(input.equals(array1));
}
}

You can use this method also to check if the string is palindrome or not.
public static boolean pallindrom(String S)
{
char arr[] = S.toCharArray();
int flag = 0;
for(int i = 0 ; i < (arr.length+1)/2 ; i++)
{
if(arr[i] != arr[arr.length-1-i])
{
flag = 1;
break;
}
}
if(flag == 0)
return true;
else
return false;
}

Related

How to use a loop to capitalize first occurring lowercase letter of string Java

Prompt: Use a loop to find the first occurring lowercase letter in the input string.
Then capitalize ONLY the lowercase letter you found, and then re-combine it with the rest of the string.
I'm so confused because one I don't know the exact number of indexes because it varies and two how can I capitalize only the first occurring lowercase. For example inputs are like BYus where I'm only supposed to capitalize the u. I have
public class PasswordImprover {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String userInput;
userInput = sc.next();
int userLowerCase = userInput.indexOf(".*[a-z].*");
for (int i = 0; i < userInput.length(); i++) {
if (Character.isLowerCase(userInput.charAt(i))) {
System.out.print(userInput.toUpperCase().charAt(i));
} else if (!userInput.contains(".*[a-z].*")) {
System.out.print(userInput.charAt(i));
}
}
}
}
but this just outputs everything in uppercase. Please help.
Get rid of that regex and just use a simple loop and a flag to indicate that you have process the first LC char
Scanner sc = new Scanner(System.in);
String userInput= sc.next();
boolean done = false;
for (int i = 0; i < userInput.length(); i++) {
if (!done && Character.isLowerCase(userInput.charAt(i))) {
System.out.print(userInput.toUpperCase().charAt(i));
done = true;
}
else {
System.out.print(userInput.charAt(i));
}
}
I'm so confused because one I don't know the exact number of indexes because it varies
Yes, that would the reason for the loop
how can I capitalize only the first occurring lowercase
Well, there's a few ways you might do it. String#substring might be starting point, for example...
public class Test {
public static void main(String[] args) {
String test = "BYus";
StringBuilder sb = new StringBuilder(test);
for (int index = 0; index < sb.length(); index++) {
if (Character.isLowerCase(sb.charAt(index))) {
test = test.substring(0, index) + Character.toUpperCase(test.charAt(index)) + test.substring(index + 1);
break;
}
}
System.out.println(test);
}
}
or, if you want to be a little more efficient, you could use a StringBuilder, for example...
public class Test {
public static void main(String[] args) {
String test = "BYus";
StringBuilder sb = new StringBuilder(test);
for (int index = 0; index < sb.length(); index++) {
if (Character.isLowerCase(sb.charAt(index))) {
sb.replace(index, index + 1, Character.toString(test.charAt(index)).toUpperCase());
break;
}
}
test = sb.toString();
System.out.println(test);
}
}
You could also convert the String to a character array and simply replace the first lower cased character in it and build a new String at the end, for example...
public class Test {
public static void main(String[] args) {
String test = "BYus";
char[] characters = test.toCharArray();
for (int index = 0; index < characters.length; index++) {
if (Character.isLowerCase(characters[index])) {
characters[index] = Character.toUpperCase(test.charAt(index));
break;
}
}
test = new String(characters);
System.out.println(test);
}
}
So, you know, options
You can iterate over the input as an array of chars:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string ");
char[] userInput = sc.next().toCharArray();
for (int i = 0; i < userInput.length; i++) {
if (Character.isLowerCase(userInput[i])) {
userInput[i] = Character.toUpperCase(userInput[i]);
break;
}
}
System.out.println(String.valueOf(userInput));
}
An example for regex.
String str = "BYus";
str = str.replaceFirst("([^a-z]*.).*", "$1").toUpperCase() + str.replaceFirst("[^a-z]*.(.*)", "$1");
System.out.println(str); //BYUs

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;
}
}

find a substring which is palindrome in given string

input is :levelmm
output is: the given string is palindrome because the given string contains level is a palindrome remain character like mm is neglected.
package example;
import java.util.Scanner;
public class exp2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("enter the string");
Scanner scan=new Scanner(System.in);
String s=scan.nextLine();
String t="";
String s1=s.substring(0, s.length()-1);
for(int i=s1.length()-1;i>=0;i--)
{
t=t+s.charAt(i);
}
if(t.equalsIgnoreCase(s1))
{
int count=t.length();
System.out.println("is palindrome"+(count-1));
}else
{
System.out.println("not a palindrome");
}
}
}
but its not working completely..
First of all, the line String s1 = s.substring(0, s.length() - 1); removes one character from your word, which is not something that looks like it's supposed to happen.
What it looks like is that you want to create every possible substring of an input and see if that is a palindrome. To see whether something is a palindrome I propose this:
private static boolean isPalindrome(String word) {
String reverseWord = "";
for (int i = word.length() - 1; i > -1; i--) {
reverseWord += word.toCharArray()[i];
}
return reverseWord.equalsIgnoreCase(word);
}
Getting every single substring is more difficult, but can be done like this:
private static String[] allSubstrings(String word) {
int amount = 0;
for (int i = 0; i < word.length() + 1; i++) {
amount += i;
}
String[] res = new String[amount];
int index = 0;
for (int i = 0; i < word.length(); i++) {
for (int j = i + 1; j < word.length() + 1; j++) {
res[index] = word.substring(i, j);
index++;
}
}
return res;
}
Now, since every word that is 1 long is a palindrome, we don't want that, so in the main method we can say a word has to be more than 1 long. This results in a main method like this:
public static void main(String[] args) {
System.out.println("enter the string");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
boolean isPal = false;
for (String word : allSubstrings(s)) {
if (word.length() > 1 && isPalindrome(word)) {
isPal = true;
}
}
if (isPal) {
System.out.println("Is palindrome");
} else {
System.out.println("Is not palindrome");
}
}
I hope this answers your question and I wish you happy coding.

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.

Categories

Resources