Recursive Palindrome Checker - java

This method only works for small inputs such as xox but not with a more complex input like taco cat. I have read this code repeatedly and have not been able to fix the problem. I assume there is a tiny error as I have changed the code structurally trying to tweak my approach and have not been able to fix it.
import java.util.Scanner;
public class Palindromes
{
static Scanner scan = new Scanner(System.in);
public static void main (String[] args)
{
System.out.println("Enter a string, human:");
String s=scan.nextLine();
if(palindrome(s)){
System.out.print("This is a palindrome, I am amused Earthling.");
}else{
System.out.print("Don't you know to speak only in palindromes to your alien Overlord?");
}
}
public static boolean palindrome(String s){
s.replace(" ","");
if(s.length()<2){
return true;
}else if(s.charAt(0)==s.charAt(s.length()-1)){
return palindrome(s.substring(1,s.length()-2));
}else{
return false;
}
}
}

Two things to fix:
You forgot to assign the result of replace back to s, resulting in you ignoring the result with spaces removed. Try:
s = s.replace(" ","");
You have an off-by-one error when taking the substring to pass to the recursive call. The ending index of substring is exclusive, so you are trimming one too many characters off the end of the substring. Try:
return palindrome(s.substring(1,s.length()-1));

Related

How to compare words of one string in Java with words of another string and separate the words on match?

This was an interview question.
You are told to take string input from user & output a string (or array of string) separated by spaces with meaningful words matching from another string called as Dictionary. You have a dictionary function to check if word exists or not.
For example:
if Input is "howareyou"
Output should be "how are you".
where the words 'how', 'are', 'you' are exist in dictionary string.
One more example:
Input: "somethingneedstobedone
Output: "something needs to be done
(Assuming that dictionary has words like something, needs, to, be, done.
I am not getting when to do k++ if there is no match.
The code I tried:
public class Sample1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int i,j,k,len;
String[] dict= {"how","are","you","something","needs","to","be","done"};
//StringBuilder str=new StringBuilder("howareyou");
StringBuilder str=new StringBuilder("somethingneedstobedone");
len=str.length();
for(i=0,j=0,k=0;i<len;i++)
{
for(j=i+1;j<len;j++)
{
if(dict[k].toString().equals(str.substring(i, j)))
{
str.insert(j, " ");
k++;
}
}
}
System.out.println(str);
sc.close();
}
The commented case works well, but help me to get second case worked.
The issue you're having (and the reason the first string succeeded and the second does not) is to do with the order of words in the dict.
Your current implementation checks if the words in the dict appear in the string exactly in the order they were entered into the dict -
after you found the first word, put in a space and proceed to find the second word. If you did not find the next word, you do not proceed with the process.
There are many ways to rewrite the code to get what you want, but the minimal change is:
public class Sample1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int i,j,k,len;
String[] dict= {"how","are","you","something","needs","to","be","done"};
//StringBuilder str=new StringBuilder("howareyou");
StringBuilder str=new StringBuilder("somethingneedstobedone");
len=str.length();
for(i=0,j=0;i<len;i++) //removed k from here
{
for(j=i+1;j<len;j++)
{
for (k=0;k<dict.length;k++) { //added this loop!
if(dict[k].toString().equals(str.substring(i, j)))
{
str.insert(j, " ");
}
} //Loop closing for k - the dictionary
}
}
System.out.println(str);
sc.close();
}

Censored Words Condition

I need this program to print "Censored" if userInput contains the word "darn", else print userInput, ending with newline.
I have:
import java.util.Scanner;
public class CensoredWords {
public static void main (String [] args) {
String userInput = "";
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine;
if(){
System.out.print("Censored");
}
else{
System.out.print(userInput);
}
return;
}
}
Not sure what the condition for the if can be, I don't think there is a "contains" method in the string class.
The best solution would be to use a regex with word boundary.
if(myString.matches(".*?\\bdarn\\b.*?"))
This prevents you from matching sdarnsas a rude word. :)
demo here
Try this:
if(userInput.contains("darn"))
{
System.out.print("Censored");
}
Yes that's right, String class has a method called contains, which checks whether a substring is a part of the whole string or not
Java String Class does have a contains method. It accepts a CharSequence object. Check the documentation.
Another beginner method would be to use the indexOf function. Try this:
if (userInput.indexOf("darn") > 0) {
System.out.println("Censored");
}
else {
System.out.println(userInput);

How can I have a user search a character array for a letter?

gets a single letter from the user. This method validates that it’s either a valid letter or the quit character, ‘!’. It'll eventually keep asking for characters, then once the user is done, they'll type ‘!’ to make the loop end and move on to printing their list of chars
public static String isValidLetter(){
char[] charArray;
charArray = new char[11];
charArray[0] ='C';
charArray[1] ='E';
charArray[2] ='F';
charArray[3] ='H';
charArray[4] ='I';
charArray[5] ='J';
charArray[6] ='L';
charArray[7] ='O';
charArray[8] ='P';
charArray[9] ='S';
charArray[10] ='T';
charArray[11] ='U';
String input;
char letter;
Scanner kb = new Scanner(System.in);
System.out.println("Enter a single character: ");
input=kb.nextLine();
letter = input.charAt(0);
Reading the strings from console.. type "a", enter, "b", enter, "!", enter
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scann = new Scanner(System.in);
List<String> letterWords = new LinkedList<String>();
String str = null;
while (!"!".equals(str)) {
str = scann.next();
letterWords.add(str);
}
for (String word : letterWords) {
System.out.println(word);
}
scann.close();
}
}
If you just want to have a "collection" of valid characters, then you also could use a String instead of an array. It would be much easier to search in it and it avoids errors like in your example (you've initialized your array with size of 11, but you're inserting 12 elements):
public static boolean isValidLetter(final char character) {
final String validCharacters = "CEFHIJLOPSTU";
return validCharacters.contains(String.valueOf(character));
}
This method expects a single char and returns true if it is valid, false otherwise. Please mind, that this check is case sensitive.
You could use that method like this:
final Scanner scan = new Scanner(System.in);
String input;
while (!(input = scan.nextLine()).equals("!")) {
if (!input.isEmpty() && isValidLetter(input.charAt(0))) {
// ... store valid input
System.out.println("valid");
}
}
This loop requests user input until he enters !. I've omitted the storing part. It is up to you to do this last part.
Modify your isValidLetter method to return boolean.
Modify your isValidLetter method to get a char as a parameter.
In isValidLetter, try to find a letter by using a helper function, something like:
static boolean contains(char c, char[] array) {
for (char x : array) {
if (x == c) {
return true;
}
}
return false;
}
Somewhere in your code where you need the input (or in main for testing), ask for user input (as you already did in isValidLetter). Perform a loop, asking for input, until it is right, or until it is your ending character.
I am not posting the complete solution code on purpose, as it is better for you to play with the code and learn. I only gave directions on how to try; of course it is not the only way, but it fits with what you've already started.

Simple Substring Issue

My teacher wants us to make a letter 'o' move around the console. The letter 'o' has been coded to appear in the center of the console screen. I have already created the movingRight and movingDown methods but I'm having difficulty creating the movingLeft and movingUp methods. Here is my code:
import java.util.Scanner;
public class Main {
static String letter = "\n\n\n\n O";
String whenmovingup = letter.substring(0, 1);
char whenmovingleft = letter.charAt(letter.length() - 2);
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(letter);
input.nextLine();
if (input.equals("left")) {
movingLeft();
}
if (input.equals("right")) {
movingRight();
}
if (input.equals("up")) {
movingUp();
}
if (input.equals("down")) {
movingDown();
}
}
public static void movingRight(){
letter = " " + letter;
}
public static void movingDown(){
letter = "\n" + letter;
}
public static void movingLeft(){
letter.remove(whenmovingleft);
}
public static void movingUp(){
letter.remove(whenmovingup);
}
}
I'm having an issue with removing the whenmovingfeft and whenmovingup substrings from my original string letter. It's giving an error ('The method remove(char) is undefined for the type String'), and I'm not sure what needs to be done.
Does anyone know how this can be resolved?
Thanks in advance for all responses.
There is no remove method for a string. However, there is a replace method that may do what you want. Note that it does not modify the string object, but it returns a new string. So you would do:
letter = letter.replace(whenmovingup, "");
Note that there are two slightly different overloads of replace which do different things depending on whether you ask it to remove a String or char. The replace(String, String) method replaces one occurrence, while the replace(char, char) replaces all occurrences. You want just one, so declare whenmovingleft as a String and initialise it appropriately.

Simple Recursion Issue Back ways

public class recursionExcercise4
{
public static void main (String[] args)
{
boolean statement=false;
String ch="";
String a="I am bubbles who is a little slugger and loves apple and yellow."
BacktoBacks(a,ch,statement);
}
public static void BacktoBacks(String sentence, String ch, boolean statement)
{
String newLine="",word="";
System.out.print(sentence.charAt(0));
if(sentence.charAt(0)=='.') System.out.println();
if(sentence.length()>1)
{
int num=sentence.substring(1).indexOf(" ");
word = sentence.substring(0,num);
System.out.println(word);
}
BacktoBacks(newLine,ch,statement);
}
}
That is the code.
The lines inside the if statement loop were added by me so you can change that but nothing else can be changed. The if statement on top must remain there. Also, I am trying to avoid loops as it makes it too easy then. Any way to do this? I tried it but need help.
The objective is to print out the words from the string that have double letters. This should also be printed backwards. So like this:
Yellow
Apple
Slugger
Little
Bubbles
Your help is much appreciated.
Thanks!!
So you need a function to check whether a word contains double letters,
public boolean hasDoubleLetters(String word){
// test
}
and based on its outcome, print the word after the recursive call. And you have to pass the correct argument to the recursive call.

Categories