views:

129

answers:

4

So my teacher told me to make a string that makes whatever I type go in the opposite order (e.g. "hello there" becomes "ereht olleh"). So far I worked on the body and I came up with this

   public class Main {

/**
 * @param args the command line arguments
 */     

  public static void main(String[] args) {
  (The input needs to be in here)}}



    public static String rev(String str) {

    String reversed = "hello there";
    for (int i = 0; i < str.length(); i++) {
        reversed = str.charAt(i) + reversed;
    }
    return reversed;

My question now is that what I need to put under the public static void main(String[] args) to make it work. Yes I understand that this is homework, I tried looking through the book for help(no luck). I tried looking on the internet(no luck thanks to my little understanding to the more advanced method). I would appreciate any help and thank anyone in advance. I use netbeans if that would help any.

+6  A: 
public static String rev(String str) {
  String reversed = "";
  for (int i = 0; i < str.length(); i++) {
      reversed = str.charAt(i) + reversed;
  }
  return reversed;
}

public static void main(String[] args) {
  if (args.length > 0) {
    System.out.println(rev(args[0]));
  }
}

Read the args array to do so.

SHiNKiROU
+2  A: 

Trying to make this as opaque as possible given the homework tag, you should, at a minimum, re-examine your initial value of reversed. The way you have it, you will end up with something other than the desired "ereht olleh".

As to your specific question on how to get the arguments from the command line, the following prints out all the arguments and would form a good basis for your own code:

public static void main (String[] args) {
    for (int i = 0; i < args.length; i++)
        System.out.println (args[i]);
    }
}
paxdiablo
+3  A: 

Few things:

Since you are adding the characters in reverse to the string reversed it should be an empty string to start with:

String reversed = "";

To call this method from main pass it the string that needs to be reversed. Something like:

public static void main(String...args[]) {
  System.out.println(rev("hello there"));
}

Alternatively you can read the string to be reversed as an input from the user and then pass it to the rev function.

codaddict
Thank you very much. It worked well for a beginner like me.
Trung Nguyen
A: 

Read console input:

public static void main(String[] args) {
  String curLine = ""; // Line read from standard in
  System.out.println("Enter a line of text");
  InputStreamReader converter = new InputStreamReader(System.in);
  BufferedReader in = new BufferedReader(converter);
  curLine = in.readLine();

  System.out.println(rev(curLine));
}
Draco Ater