JAVA Assignment, Need Help! Create a project called Inlab12 and make a class cal
ID: 3820882 • Letter: J
Question
JAVA Assignment, Need Help!
Create a project called Inlab12 and make a class called Recursion.
>Make a static method that changes all 'x' characters in an input String into 'y' characters (return the String). E.g. "sxmeinpxtstrxng" -> "symeinpytstryng".
>Make a static method that moves all 'x' characters in an input String to the end of the String (return the String). E.g. "sxmeinpxtstrxng" -> "smeinptstrngxxx".
>Make a static method that returns the number of times the digit 7 appears in an input int. E.g. 487264719 -> 2.
>Make a Driver that does some simple tests of your methods.
You cannot use Loops, only Recursive functions.
If possible, the code should be relatively simple and beginner friendly.
Thank You.
Explanation / Answer
public class Recursion {
public static String changeX(String input) {
String result = String.valueOf(input);
return result.replace("x", "y");
}
public static String moveX(String input) {
String result = String.valueOf(input);
int charCount = result.replaceAll("[^x]", "").length();
result = result.replaceAll("x", "");
while(charCount-- != 0) {
result += "x";
}
return result;
}
public static int countDigit(int number, int digit) {
int count = 0;
while(number != 0) {
if(number % 10 == digit)
count++;
number = number/10;
}
return count;
}
public static void main(String args[]) {
System.out.println("Changing x in string sxmeinpxtstrxng : " + changeX("sxmeinpxtstrxng"));
System.out.println("Moving x in string sxmeinpxtstrxng back: " + moveX("sxmeinpxtstrxng"));
System.out.println("Counting digit 7 in 487264719 : " + countDigit(487264719, 7));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.