You can use this:
new StringBuilder(hi).reverse().toString()
StringBuilder was added in Java 5. For versions prior to Java 5, the StringBuffer class can be used instead — it has the same API.
You can use this:
new StringBuilder(hi).reverse().toString()
StringBuilder was added in Java 5. For versions prior to Java 5, the StringBuffer class can be used instead — it has the same API.
For Online Judges problems that does not allow StringBuilder or StringBuffer, you can do it in place using char[] as following:
public static String reverse(String input){
char[] in = input.toCharArray();
int begin=0;
int end=in.length-1;
char temp;
while(end>begin){
temp = in[begin];
in[begin]=in[end];
in[end] = temp;
end--;
begin++;
}
return new String(in);
}
Videos
Problem in Q=Q-- and ; symbol after for cylce. Try this:
class Play{
void REVERSE (){
String [] INPUT_WORD = {"T","R","A","I","N"};
int Q;
for(Q=INPUT_WORD.length-1; Q>=0; Q--) {
System.out.print(INPUT_WORD[Q]);
}
}
public static void main(String[]args){
Play PL = new Play();
PL.REVERSE();
}
}
I'd like to offer a few suggestions.
Indent your code. It not only makes it easier for you to follow, but makes it easier for others to read your code.
Naming conventions. Use Title case for classes, camelCase for both variables and methods, and UPPER_CASE for constants.
Strings and characters. A String can be decomposed into an array of characters with the built-in method,
String.toCharArray(). A character array is mutable, so is often used as an intermediate structure when converting a String from one state to another for tasks like ciphers or interview problems.Encapsulation. If you can make your methods use only what is submitted to them through their method signature, and only output their return value, it's usually best. Prefer passing values over referencing constants in your utility methods to make them easier to follow.
package abnpackage; class Play { private static final String INPUT_WORD = "TRAIN"; private String reverse(String word) { char[] letters=word.toCharArray(); StringBuilder sb=new StringBuilder(); for (int q=letters.length-1; q>=0; q--) { sb.append(letters[q]); } return sb.toString(); } public static void main(String[]args) { Play play = new Play(); System.out.println("REVERSE VALUE: " + play.reverse(INPUT_WORD)); } }