recursive expand of strings - java

I want to create a method which recursively expands the input string with another string.
public class StringTest {
public static String addZeichenkette(String out, int i) {
out += "bla";
if (i > 0) {
i--;
addZeichenkette(out, i);
}
return out;
}
public static void main(String[] args) {
String out = "Hello";
out = addZeichenkette(out, 7);
System.out.println(out);
}
}
The output should be :
Helloblablablablablablabla
instead it is
Hellobla
The main method has to be untouched (except the method calling).

You're ignoring the return from the recursive call.
public static String addZeichenkette(String out, int i)
{
if (i > 0)
{
out += "bla";
i--;
out = addZeichenkette(out, i);
}
return out;
}
Alternatively, you could just return the result addZeichenkette(out, i);, but both ways are fine.
As you pointed out, you would need to modify it to avoid adding i+1 bla's. Since when i = 0, we don't want any bla's to be added, we instead need to check for this.
To do this, I moved the concatenation of the bla into the condition.

You need to return the accumulated (recursed) string:
return addZeichenkette(out, i);
not just the one where i == 0.
public static String addZeichenkette(String out, int i) {
return i > 0 ? addZeichenkette(out + "bla", --i ) : out;
}

Related

Recursive Method to find number of occurrences of UpperCase letters in string- Using helper method

I'm trying to create a recursive method to find the number of occurrences of an UpperCase letter in a String. My code below:
public class findUppercase {
public static int searchUppercase(String s, int high) {
if (s.length() == 1) {
if (Character.isUpperCase(s.charAt(0)))
return 1;
else
return 0;
} else if (Character.isUpperCase(s.charAt(high - 1)) )
return 1 + searchUppercase(s, s.length() - 1);
else
return searchUppercase(s, s.length() - 1);
}
public static int searchUppercase(String s) {
return searchUppercase(s, s.length());
}
public static void main(String[] args) {
String a = "ABCmdsaA";
System.out.println(searchUppercase(a));
}
}
I get the error:
Exception in thread "main" java.lang.StackOverflowError
at java.lang.Character.getType(Character.java:6924)
at java.lang.Character.isUpperCase(Character.java:5518)
at java.lang.Character.isUpperCase(Character.java:5488)
at findUppercase.searchUppercase(findUppercase.java:9)
As your String is never changing, its length will never change, so
if (s.length() == 1) {
will never be true unless you originally pass in a one char String
Change the value of the String s by using String.substring
Although personally I would just use a for loop and not a recursive method.
You don't need a recursive method at all, nor a for loop.
Just do:
public static long searchUppercase(String s) {
return s.chars()
.filter(i -> Character.isUpperCase(i))
.count();
}
But if you insist on using a recursive method, you only need a single uppercase check and a single recursive call:
public static long searchUppercase(String s, long count) {
if (s.length() == 0) {
return count;
}
if (Character.isUpperCase(s.charAt(0))) ++count;
String tail = s.substring(1);
return searchUppercase(tail, count);
}
public static long searchUppercase(String s) {
return searchUppercase(s, 0);
}

how return System.out.print(0) in a void method?

I am making a basic decimal-to-binary converter for a class and its set up for when the user enters a '0' for it to return a zero. I am not sure how to do that with a return statement.
public class binary1
{
public static void main(String[] args)
{
int input = Integer.parseInt(args[0]);
convert(input);
System.out.println();
}
public static void convert( int input )
{
if (input == 0) return System.out.print(0); //<-- here is my problem
convert(input / 2);
System.out.print(input % 2);
}
};
Put your return after the print line. I am assuming you do not actually need to return a value but to exit the function.
public static void convert( int input )
{
if (input == 0)
{
System.out.print(0);
return;
}
convert(input / 2);
System.out.print(input % 2);
}
I am little confused what exactly you want but here is some modified code might help you.
public static int convert(int input) {
if (input == 0){
System.out.print(0);
return 0 ;
}
convert(input / 2);
System.out.print(input % 2);
}
The method you have posted fails to return anything.
If you intend to return the integer converted to binary, the simplest approach would be to return it as a String, like so:
public static String convert(int input) {
if (input == 0)
return "0";
else
return convert(input / 2) + (input % 2);
}
Note: You can simply use Integer.toBinaryString(input) to perform exactly this.

Java contains a string or not?

http://codingbat.com/prob/p126880
Given two strings, return true if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: str.toLowerCase() returns the lowercase version of a string.
I cannot get when it is true, it always gives false.
public boolean endOther(String a, String b)
{
//variables
a.toLowerCase();
b.toLowerCase();
String f1="";
String f2="";
int d=0;
int sum=0;
//Program code;
if(a.length()-b.length()>0)
{
(f1).equals(a);
(f2).equals(b);
d=a.length();
}
else if(a.length()-b.length()<0)
{
(f1).equals(b);
(f2).equals(a); //gett**ing bigger and lower String**
d=b.length();
}
else if((a).equals(b))
sum++;
// I think problem is because it is not enter the for.
for(int i=0; i>d; i++)
{
if((f1.substring(i,i+f2.length())).equals(f2))
sum++;
}
if(sum>0)
return true;
else
return false;
}
This is a working example of what you are trying to achieve to test in your Java IDE like Netbeans or Eclipse whatever. This is really simple, the String object has an endsWith method so why try to invent something yourself.
If you have any troubles reading this code hit me up, should be quite straight forward. You will just have to convert your string to lowercase, that's for you to add.
public class StringEnds {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.printf("String a: ");
String a = scanner.next();
System.out.printf("String b: ");
String b = scanner.next();
// Compare a and b
if (endsWith(a, b)) {
System.out.printf("Succes\n");
} else {
System.out.printf("Fail\n");
}
}
public static boolean endsWith(String firstString, String secondString) {
return firstString.endsWith(secondString) || secondString.endsWith(firstString);
}
}
Here's your codebat solution (it is quite short):
public boolean endOther(String a, String b) {
return a.toLowerCase().endsWith(b.toLowerCase()) || b.toLowerCase().endsWith(a.toLowerCase());
}
This is my answer. I tried both ways, hope it helps.
public boolean endOther(String a, String b) {
int small = Math.min(a.length(), b.length());
if (a.length()==b.length() && a.equalsIgnoreCase(b)) {
return true;
}
if (small==a.length()) {
if (b.substring(b.length()-small).equalsIgnoreCase(a)) {
return true;
}
// from here is the toLowerCase() method.
a = a.toLowerCase();
b = b.toLowerCase();
} else if (small==b.length()) {
if (a.endsWith(b)) {
return true;
}
}
return false;
}

Error in my Word program in Java

This is my code and it compiles fine but when I try to create a string it says
Error: cannot find symbol - variable racer
public class Word {
private String original;
public Word(String s) {
original = s;
}
public String reverse () {
String reverse= "";
int x = 1;
int length = original.length();
while (length - x >= 0) {
reverse = reverse + original.substring(length -x);
x++;
}
return reverse;
}
public boolean isPalindrome() {
if(original.equals(reverse()))
return true;
else
return false;
}
}
The stated problem is not in the code posted - my guess is irrelephant's comment is correct, ie change new Word(racer) --> new Word("racer").
But I offer this to eliminate any chance of any errors in your code by basically eliminating your code:
public class Word {
private String original;
public Word(String s) {
original = s;
}
public boolean isPalindrome()
return new StringBuilder(original).reverse().toString().equals(original);
}
}
or if you must expose a reverse() method:
public class Word {
private String original;
public Word(String s) {
original = s;
}
public String reverse () {
return new StringBuilder(original).reverse().toString();
}
public boolean isPalindrome()
return reverse().equals(original);
}
}
I don't see the variable racer anywhere, but since you're using reverse inside a method, I'd recommend making it
Most likely, racer was never defined
Either that or the method was called w/o quotes
isPalindrome(racer)//note the lack of quotes
change reverse() to this
private() String reverse () {
String reverse= "";
int x = 1;
int length = original.length();
while (length - x >= 0) {
reverse = reverse + original.substring(length -x);
x++;
}
return reverse;

how to uncompress a given string in java recursively?

this is very easy using iteration but i have to do this using recursion. I tried to keep a count of how many times a char occurs in a string, the position and the rest of the string and output.
public static String uncompress(String compressedText) {
return uncompress(compressedText, 1, 0, "");
}
public static String uncompress(String text, int count, int pos, String output) {
if (text.equals("")) {
return "";
}
if (Character.isLetter(text.charAt(pos))) {
output += text.charAt(0);
pos++;
}
else if(Character.isDigit(text.charAt(pos))) {
count = text.charAt(pos) - '0';
output += text.charAt(pos + 1);
count++;
pos++;
}
text = text.substring(pos + 1);
uncompress(text, count, pos, output);
return output;
}
There are multiple errors in your code such as:
you are substringing but also passing in a position, you should do one or the other
your base case is returning "" but instead it should return the accrued string 'output'
where you recurse you disregard the output from the returning method and just return the output in the current method so nothing is built up by the recursion
Below is code which uses only recursion both to parse the string and build up the output. I have added comments to show what is happening in the code. Note that, particularly in recursion, it is useful to have a printout of the current state so you can see what is happening at each stage so I have added this too.
Note that the getMultiple() method is in itself a very simple example of how recursion should work - that you call the same method but either A) pass in some work done in the current call so that it can be accrued by the base case or B) take the output of the method and add something to it / modify it before returning the modified output.
public class Recursion {
public static void main(String[] args) {
System.out.println(uncompress("10a2b"));
}
public static String uncompress(String compressedText) {
return uncompress(compressedText, "", "");
}
public static String getMultiple(char x, int N) {
if (N == 0) return "";
return ""+x+getMultiple(x,N-1);
}
public static String uncompress(String text, String count, String output) {
System.out.println("----");
System.out.println("TEXT:"+text);
System.out.println("COUNT:"+count);
System.out.println("OUTPUT:"+output);
if (text.equals("")) {
//base case - no text left to parse
return output;
}
if (Character.isLetter(text.charAt(0))) {
//letter case - need to take the count we have accrued, parse it into an integer and add to output
System.out.println(count);// * text.charAt(0);
output += getMultiple(text.charAt(0),Integer.parseInt(count));
count = "";
}
else if(Character.isDigit(text.charAt(0))) {
//digit case - need to add to the count but keep as a string because must be parsed later
count += (""+text.charAt(0));
}
//parse the *remainder* of the string, one character at a time, so pass in the substring(1)
return uncompress(text.substring(1), count, output);
}
}
Assuming that the input String has a correct format, try this:
public static String uncompress(String compressedText) {
if (compressedText.length() == 0)
return "";
return uncompress(compressedText, charToInt(compressedText, 0), 0);
}
public static String uncompress(String text, int count, int pos) {
if (pos == text.length() || (pos == text.length()-2 && count == 0))
return "";
else if (count == 0)
return uncompress(text, charToInt(text, pos+2), pos+2);
return text.charAt(pos+1) + uncompress(text, count-1, pos);
}
public static int charToInt(String str, int idx) {
return str.charAt(idx) - '0';
}

Categories