Question

In: Computer Science

How would you write the following recursively? This is in Java.    public static String allTrim(String...

How would you write the following recursively? This is in Java.


  

public static String allTrim(String str) {
int j = 0;
int count = 0; // Number of extra spaces
int lspaces = 0;// Number of left spaces
char ch[] = str.toCharArray();
int len = str.length();
StringBuffer bchar = new StringBuffer();
if (ch[0] == ' ') {
while (ch[j] == ' ') {
lspaces++;
j++;
}
}

for (int i = lspaces; i < len; i++) {
if (ch[i] != ' ') {
if (count > 1 || count == 1) {
bchar.append(' ');
count = 0;
}
bchar.append(ch[i]);
} else if (ch[i] == ' ') {
count++;
}
}
return bchar.toString();
}

Solutions

Expert Solution

Solution:

class Main

{

//recursive function

static String trimAll(String str, int start, int end)

{

if(str.charAt(start)!=' ' && str.charAt(end)!=' ')

{

return str.substring(start, end+1);

}

else if(str.charAt(start)==' ' && str.charAt(end)!=' ')

{

return trimAll(str, start+1, end);

}

else if(str.charAt(start)==' ' && str.charAt(end)==' ')

{

return trimAll(str, start+1, end-1);

}

else

{

return trimAll(str, start, end-1);

}

}

//main function

public static void main(String[] args) {

String str = " India ";

//length of original string

System.out.println("Original string = "+str+ "\nOriginal string length = "+str.length());

String result = trimAll(str, 0, str.length()-1);

//to count extra spaces you just need to get the length difference

int extraSpaces = str.length() - result.length();

System.out.println("Extra spaces = " +extraSpaces);

//length of string after trimming

System.out.println("Resultant string = "+result+ "\nResultanat string length = " +result.length());

}

}

Output:

​​​​​​​

Please give thumbsup, if you like it. Thanks.


Related Solutions

How do you write a Java method that is called : public static String[] noIdenticalCombine(String[] array1,...
How do you write a Java method that is called : public static String[] noIdenticalCombine(String[] array1, String[] array2) { // instructions: returns an array that contains all the Strings in array1 and array2 but without repetition. order does not matter, but it will return array1's elements and then array2's element that are not in array1. Assume there are no duplicates are in array1 and array2. Could use count which is how many str there are in array2, where !contains(array1, str)....
Write in Java: Write a method called: public static String[] noIdenticalCombine(String[] array1, String[] array2) { //...
Write in Java: Write a method called: public static String[] noIdenticalCombine(String[] array1, String[] array2) { // instructions: returns an array that contains all the Strings in array1 and array2 but without repetition. order does not matter, but it will return array1's elements and then array2's element that are not in array1. Assume there are no duplicates are in array1 and array2. Could use count which is how many str there are in array2, where !contains(array1, str). May an array of...
Write program in Java import java.util.Scanner; public class Lab7Program { public static void main(String[] args) {...
Write program in Java import java.util.Scanner; public class Lab7Program { public static void main(String[] args) { //1. Create a double array that can hold 10 values    //2. Invoke the outputArray method, the double array is the actual argument. //4. Initialize all array elements using random floating point numbers between 1.0 and 5.0, inclusive    //5. Invoke the outputArray method to display the contents of the array    //6. Set last element of the array with the value 5.5, use...
WRITE THIS JAVA CODE IN PSEUDOCODE!! import java.util.Scanner; public class License { public static void main(String[]...
WRITE THIS JAVA CODE IN PSEUDOCODE!! import java.util.Scanner; public class License { public static void main(String[] args) { char correctAnswers[] = {'B', 'D', 'A', 'A', 'C', 'A', 'B', 'A', 'C', 'D', 'B', 'C', 'D', 'A', 'D', 'C', 'C', 'B', 'D', 'A'}; char userAnswers[] = new char[correctAnswers.length]; Scanner scanner = new Scanner(System.in); for (int i = 0; i < userAnswers.length; i++) { String answer = ""; System.out.printf("Question #%d. Enter your answer( A, B, C or D): ", i + 1); do...
write a java program that allows main to work public static void main(String[] args) { /*...
write a java program that allows main to work public static void main(String[] args) { /* Start with the empty list. */ LinkedList list = newLinkedList(); // // ******INSERTION****** // // Insert the values deleteFront(list); deleteBack(list); list = insert(list, 1); list = insert(list, 2); list = insert(list, 3); list = insert(list, 4); list = insert(list, 5); list = insert(list, 6); list = insert(list, 7); list = insert(list, 8);    // Basic Operations on the LinkedList printList(list); insertFront(list,0); printList(list); insertBack(list,999); printList(list);...
Please don't just copy another solution. Write the following Java program: public static String getFlag(int size,...
Please don't just copy another solution. Write the following Java program: public static String getFlag(int size, char color1, char color2, char color3) - This method returns a string where a triangle appears on the left size of the diagram, followed by horizontal lines. For example, calling DrawingApp.getFlag(9, 'R', '.', 'Y'); will generate the string: R............................................ RRYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY RRRYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY RRRRYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY RRRRRYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY RRRRRRYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY RRRRRRRYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY RRRRRRRRYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY RRRRRRRRR.................................... RRRRRRRRR.................................... RRRRRRRRYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY RRRRRRRYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY RRRRRRYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY RRRRRYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY RRRRYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY RRRYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY RRYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY R............................................ The diagram has a number of rows that...
DESCRIBE WHAT THE FOLLOWING JAVA CODE DOES: public class Main{ public static void main(String[] args) {...
DESCRIBE WHAT THE FOLLOWING JAVA CODE DOES: public class Main{ public static void main(String[] args) { new MyFrame(); } } import javax.swing.*; public class MyFrame extends JFrame{ MyPanel panel; MyFrame(){ panel = new MyPanel(); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.add(panel); this.pack(); this.setLocationRelativeTo(null); this.setVisible(true); } } import java.awt.*; import javax.swing.*; public class MyPanel extends JPanel{ //Image image; MyPanel(){ //image = new ImageIcon("sky.png").getImage(); this.setPreferredSize(new Dimension(500,500)); } public void paint(Graphics g) { Graphics2D g2D = (Graphics2D) g; //g2D.drawImage(image, 0, 0, null); g2D.setPaint(Color.blue); g2D.setStroke(new BasicStroke(5)); g2D.drawLine(0, 0, 500,...
// problem2.java import java.util.*; public class problem_a { public static void main(String[] args) { // test...
// problem2.java import java.util.*; public class problem_a { public static void main(String[] args) { // test the smallest method System.out.print("smallest(1, 0, 2) -> "); System.out.println( smallest(1, 0, 2) ); // test the average method System.out.print("average(95, 85, 90) -> "); System.out.println( average(95, 84, 90) ); } // end main /* * smallest(double, double, double) -> double * * method is given 3 numbers, produces the smallest of the three * * examples: * smallest(1, 0, 2) -> 0.0 */ public static...
FOR JAVA: Need to write a code for the implementation of this public static method: findLongestPalindrome...
FOR JAVA: Need to write a code for the implementation of this public static method: findLongestPalindrome takes a Scanner scn as its parameter and returns a String. It returns the longest token from scn that is a palindrome (if one exists) or the empty string (otherwise). (Implementation note: You'll find your isPalindrome method helpful here. This method calls for an optimization loop.)
I am struggling with this java code ublic class HW2_Q4 {    public static void main(String[]...
I am struggling with this java code ublic class HW2_Q4 {    public static void main(String[] args) {        // Define the input string. Note that I could have written it all on a        // single line, but I broke it up to match the question.        String input = "Book , Cost , Number\n"                    + "Hamlet , 24.95 , 10\n"                    + "King Lear , 18.42...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT