Home > database >  Making the sentence (array) in reverse
Making the sentence (array) in reverse

Time:11-21

It's my homework but I'm not sure what to do with it.. PLZ HELP!I need to know what A, B, C s after 'for' are..! Oh and I need explanations as well using (//)!

 Use the method below. Other methods allowed. 
 
class Reverse {
public void reverseW(String s) {
  String[ ] strArray = s.split(" ");
         StringBuffer sb = new StringBuffer();
         for (              A                    ) {
         if (strArray[i].trim().length()    B    ) {
          sb.append           C           ; 
         }
         }
         System.out.println(sb);
}
}
 
public class ReverseWords {
public static void main(String[ ] args) {      
              String str = "Hello JAVA world!";
              System.out.println(str);
        
              Reverse sol = new Reverse();
              sol.reverseW(str);
  }
 
}
 
Result>>
Hello Java Programming!
Programming! Java Hello
 

I tried to use other methods but errors are keep popping out..

CodePudding user response:

This is Answer of your question---

package com.string; // this is our package

public class reverseString { // this is our class

public static void main(String[] args) { // main method

String s = "Hello Java Programming!";

 for(int i=s.length();i>0;i--) {   

// uesd for loop and default length method

System.out.print(s.charAt(i-1));

 }
} 
}
}

Result- !gnimmargorP avaJ olleHeH

CodePudding user response:

The code below is the answer of the question. Hope the answer helps you.

  1. the loop condition is start at the end of the strArray, meaning that we are loop from the end of the last word of the sentence. And the condition is end when the condition meet the first word of the sentence.
  2. strArray[i].trim().length() != 0 means to escape empty word, which maybe not a true word in sentence.
  3. append() method meaning append word to the result, don't forget to append space after the word.(You can do a special check here to avoid the a space following last word).
public void reverseW(String s) {
    String[] strArray = s.split(" ");
    StringBuffer sb = new StringBuffer();
    for (int i = strArray.length - 1; i>= 0; i--) {
        if (strArray[i].trim().length() != 0){
            sb.append(strArray[i]).append(" ");
        }
    }
    System.out.println(sb);
}

Besides, you can use enhanced-for to do a clearly loop.

  • Related