StackOverflow when checking if one string is contained in another - java

I currently have a method that is supposed to take two strings and then check if one string exists as a substring in other. It doesn't check both ways so the way in which I pass my strings to the method determines what string is looked for in the other.
Currently I am getting a stackoverflow error.
public boolean checkMatch(String text, String regex, int i){
int regexL = regex.length();
if(i == regexL){
return true;
}
System.out.println(text.charAt(i) + " " + regex.charAt(i));
if(text.charAt(i) == regex.charAt(i)){
return checkMatch(text, regex, i++);
}
else if(text.charAt(i) != regex.charAt(i)){
if(text.substring(1) == ""){
return false;
}
else if(text.substring(1) != ""){
return checkMatch(text.substring(1), regex, 0);
}
}
return false;
}
I am running a test using my first name as an example.
#Test public void test_52() {
assertEquals(true, checkMatch("Samual", "mu", 0));
}
the console looks like this after it overflows.
S m
a m
m m
m m
m m
etc
Where am I going wrong? Am I iterating wrong? The stack trace shows that it seems to be getting caught on this line.
return checkMatch(text, regex, i++);
But the defect point is rarely the point of failure. Sorry for the wall of text and code.

I don't know if the rest is correct, but here is one error: i++increments i after it was evaluated. You call your function with the same value every time. You probably mean ++i.

You have:
return checkMatch(text, regex, i++);
You mean:
return checkMatch(text, regex, ++i);
Or:
return checkMatch(text, regex, i + 1);
The problem with i++ there is post-increment evaluates to i before the increment, so you're just getting stuck without advancing i, and eventually the recursion overflows the stack.
Had you printed i in your debugging output, the problem may have been clearer.

You can just use the indexOf method:
System.out.println("Samual".indexOf("mu") > 0);
Output:
true

Related

Shift a number to the beginning of a string recursive Java

The task is to shift a number within a string to the beginning of the string with a recursion. So if I feed "ba3nana" to the code it should return "3banana". Did some recursive tasks already but this one I am stuck on.
I tried I guess already 50 different combinations but so far my code only returns "banana3" so I go the opposite way with my number. Does anyone see the mistake in my code?
The call of the method looks like this:
System.out.println(shiftDigitLeft("ba3nana"));
This is the code so far:
private static String shiftDigitLeft(String text) {
if (text.isEmpty()) {
return text;
} else {
if (text.charAt(0) >= '\u0030' && text.charAt(0) <= '\u0039') {
return shiftDigitLeft(text.substring(1)) + text.charAt(0);
} else {
return text.charAt(0) + shiftDigitLeft(text.substring(1));
}
}
}
Thanks in advance!
The pseudocode for what you've written would look like this
String shiftDigitLeft(String text) {
if the text is empty
return empty
else
if the first character is a digit
return shiftDigitLeft(the rest of the string) + the digit
else
return the letter + shiftDigitLeft(the rest of the string)
}
It should be obvious from this that digits never get moved to the left, only to the right.
You should probably invert your approach so that you look whether the last character is a digit, and if it is then move it to the beginning.

String Symmetry Program

Hey I could use a little bit of help to figure out why my program isn't working. The question is to make a program using recursion that figures if it the text given is a palindrome or not after all the punctuation and white spaces are removed. While the program so far compiles, it returns every value as false. We are only allowed to change the isSymmetrical method. I could use whatever help possible trying to figure out how to make this work. Thank you.
public class StringSymmetry {
public static boolean isSymmetrical(String inputText)
{
if(inputText.length() == 0 || inputText.length() ==1)
return true;
if(inputText.charAt(0) == inputText.charAt(inputText.length()-1))
return isSymmetrical(inputText.substring(1,inputText.length()-1));
return false;
}
public static void main(String[] args) {
String[] sampleData =
{ "Don't nod",
"Dogma: I am God",
"Too bad - I hid a boot",
"Rats live on no evil star",
"No trace; not one carton",
"Was it Eliot's toilet I saw?",
"Murder for a jar of red rum",
"May a moody baby doom a yam?",
"Go hang a salami; I'm a lasagna hog!",
"Name is Bond, James Bond"
};
for (String s : sampleData)
{
System.out.println("isSymmetrical (" + s + ") returns " + isSymmetrical(s));
}
}
}
The problem is that you didn't include any checks for case or punctuation and white space.
One way you could do it is something like this. The specifics depend on what you're allowed to use for the assignment, but you're probably intended to do something along these lines.
Also, note that toLowerCase is problematic if you have the default locale set to something unusual like Turkey. For proper robustness, you need to specify a locale, but this isn't something you'll have to worry about in a homework assignment.
public static boolean isSymmetrical(String inputText)
{
inputText = inputText.toLowerCase();
if(inputText.length() == 0 || inputText.length() ==1)
return true;
if(!Character.isLetter(inputText.charAt(0)))
return isSymmetrical(inputText.substring(1,inputText.length()));
if(!Character.isLetter(inputText.charAt(inputText.length()-1)))
return isSymmetrical(inputText.substring(0,inputText.length()-1));
if(inputText.charAt(0) == inputText.charAt(inputText.length()-1))
return isSymmetrical(inputText.substring(1,inputText.length()-1));
return false;
}
Check the following function:
public static boolean isPalindrome(String str, int x) {
if(x == 0) return true;
if(str.charAt(0) == str.charAt((str.length() - 1)))
return isPalindrome(str.substring(1, str.length() - 1), x - 1);
return false;
}
Explanation:
A recursive function with the following parameter's:
str - a String object which will be tested for symmetry.
x - Integer that represent's the recursive tester parameter and decides for how far you want to iterate and check for two sided symmetry.
The base case is set to zero and return's true when you finished the desired iteration number.
The second if-condition statement is used to check the corner's of the string that is given, and its return statement will recursively enter another testing loop with shorter corner's of the original String( . . . corner's will be shorter by one).

Programming java to a symmetrical word [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Programming java to determine a symmetrical word
am new here, but I am having hard time figuring out how to write a code to determine an input of word and see if the first is matching with the end of the word. You may input abba and get answer it's evenly symmetric and aba is oddly symmetric.
Please show me how:(
Just two main things.
first I want to know if it's oddly or evenly amount of letter(number of letter divided by 2,if it's ending with 0.5, it's oddly symmetric, if is an integer it's evenly symmetric.
second I want to get (i.e 1=n,2=n-1,3=n-2...) position of the letter in the word to be the main idea of the execution.If there is a last letter in the oddly symmetric word, ignore the last remaining letter.
I appreciate any headstart or idea:) Thanks!
Thanks KDiTraglia, I made the code and compiled and here is what I put. I am not getting any further.
Reported problem:
Exception in thread "main" java.lang.Error: Unresolved compilation problems: reverse cannot be resolved or is not a field reverse cannot be resolved or is not a field Syntax error, insert ") Statement" to complete IfStatement
This is what i got from, KDiTraglia's help
public class WordSymmetric {
public static void main(String[] args) {
String word = "abccdccba";
if ( (word.length() % 2) == 1 ) {
System.out.println("They are oddly symmetric");
//odd
}
else {
System.out.println("They are evenly symmetric");
//even
}
int halfLength = word.length() / 2;
String firstHalf = word.substring(0, halfLength);
String secondHalf = word.substring(halfLength, word.length());
System.out.println(secondHalf.reverse());
if (firstHalf.equals(secondHalf.reverse()) {
System.out.println("They match");
//they match
}
} }
String does not have a reverse method. You could use the apache commons lang library for this purpose:
http://commons.apache.org/lang/api-release/org/apache/commons/lang3/StringUtils.html#reverse%28java.lang.String%29
The reverse() approach is very clean and readable. Unfortunately there is no reverse() method for Strings. So you would either have to take an external library (StringUtils from the appache common lang3 library has a reverse method) or code it yourself.
public static String reverse(String inputString) {
StringBuilder reverseString = new StringBuilder();
for(int i = inputString.length(); i > 0; --i) {
char result = inputString.charAt(i-1);
reverseString.append(result);
}
return reverseString.toString();
}
(This only works for characters that can fit into a char. So if you need something more general, you would have to expand it.)
Then you can just have a method like this:
enum ePalindromResult { NO_PALINDROM, PALINDROM_ODD, PALINDROM_EVEN };
public static ePalindromResult checkForPalindrom(String inputStr) {
// this uses the org.apache.commons.lang3.StringUtils class:
if (inputStr.equals(StringUtils.reverse(inputStr)) {
if (inputStr.length % 2 == 0) return PALINDROM_EVEN;
else return PALINDROM_ODD;
} else return NO_PALINDROM;
}
System.out.println(secondHalf.reverse());
There is no reverse() method defined fro String
I would probably loop over word from index 0 to the half (word.length() / 2) and compare the character at the current index (word.charAt(i)) with the correspoding from the other half (word.charAt(word.length() - i).
This is just a rough draft, you probably need to think about the loop end index, depending on oddly or evenly symmetry.
You can adapt this :
final char[] word = "abccdccba".toCharArray(); // work also with "abccccba"
final int t = word.length;
boolean ok = true;
for (int i = t / 2; i > 0; i--) {
if (word[i - 1] != word[t - i]) {
ok = false;
break;
}
System.out.println(word[i - 1] + "\t" + word[word.length - i]);
}
System.out.println(ok);
Console :
c c
c c
b b
a a
true
Use class StringBuffer instead of String

printing a mirrored word using recursion

i need to write a method that takes in a string as a parameter and prints the word in mirrored form. for example, "hello" should return "helloolleh". I have to use recursion and cannot use for loops. Here is my code so far:
public static String printMirrored(String str)
{
if(str == null || str.equals(""))
{
return str;
}
else
{
return str + printMirrored(str.substring(1)) + str.charAt(0);
}
}
My output is "helloellollolooolleh" which obviously has some extra things in there. Any pointers would be greatly appreciated!
Try using str.charAt(0) at the beginning instead of str.
Wrote this real quick. Should do exactly what you want but if you have any questions please let me know.
String word = "hello";
System.out.println(reverseWord(word, word.length()));
public static String reverseWord(String word, int length) {
if(length == 0)
return word;
else
return reverseWord(word + word.charAt(length - 1), length - 1);
}
Recursion is about being the utmost lazy person delegating the rest to a recursive clone.
So on "Hello", take only the "H", get the mirrored result of "ello" and surround it on both ends with an "H".
use StringBuilder.reverse()

Whitespace detector returning errors

I created a method to basically detect white space characters. I go through a string and check each character for white space. If it is a white space character, I return true, and if it's not, I return false. However, I get a compilation error, stating "missing return statement". As I already have two return statements "true" and "false", I can't see why there is an error. Can you help me out or point me in the right direction? Thanks in advance.
public boolean isWhitespace()
{
for (int i=0; i<string.length(); i++)
{
if (Character.isWhitespace(i))
{
return true;
}
else
{
return false;
}
}
}
Imagine if string.length() were 0. What would get returned?
Also, note that this doesn't do what you stated, which is to go through a string and check each character. It actually isn't checking anything about the string at all because of your use of i. If it were checking the string, it still would only check the first character of the string. If that character is whitespace, true is immediately returned, and if not, false is immediately returned.
You are looping over the length of the String, yet trying to return inside that loop. The logic doesn't make sense.
Think about the problem you are trying to solve - do you want to test if a character is a whitespace, or if an entire String contains at least one whitespace character? For the latter:
boolean hasWhite = false;
for(int i=0; i < string.length(); i++)
{
if(Character.isWhitespace(string.charAt(i)))
{
hasWhite = true;
break;
}
}
return hasWhite;
EDIT: A much simpler approach, if you're into that sorta thing ;-) -
return string.contains(" ");
Here is what your code should look like:
public boolean isWhitespace(String string) { // NOTE: Passing in string
if (string == null) { // NOTE: Null checking
return true; // You may consider null to be not whitespace - up to you
}
for (int i=0; i < string.length(); i++) {
if (!Character.isWhitespace(string.charAt(i))) { // NOTE: Checking char number i
return false; // NOTE: Return false at the first non-whitespace char found
}
}
return true; // NOTE: Final "default" return when no non-whitespace found
}
Note that this caters for the edge cases of a blank (zero-length) string and a null string

Categories