1
votes

Pretty new to Java programming, but I'm having trouble getting this to run. I want to read in a word using the StringBuffer class, then reverse it. I am fairly unfamiliar with importing Java libraries, so I'm not sure if I did that correctly. Either way, this is what I have. I tried to compile it (I'm working in the Terminal), but got a few compiler errors. Any help would be appreciated.

import java.util;
import java.io;

public class HW1A {

  public static void main (String[] args) {
     printBackwards();
  }

  public static void printBackwards (String[] args) {
     StringBuffer backwards = new StringBuffer(args);
     System.out.println(backwards.reverse());
  }

}

I get the following complier errors:

HW1A.java:1: cannot find symbol symbol : class util location: package java import java.util; ^ HW1A.java:2: cannot find symbol symbol : class io location: package java import java.io;

Thanks.

5
What errors did you get and on which lines? - Tom Zych
can you put the error messages into the question please. It will help people who search for those in the future. - Preet Sangha
Please tag as homework if it is. - Paul Bellora
Use an IDE, for goodness' sake. stackoverflow.com/questions/4577055/… - Blessed Geek
Really, listen to Blessed Geek and download one of the free IDE's. You will actually learn faster using one. - Perception

5 Answers

8
votes

Since this is a learning exercise have a look at printBackwards, and ask yourself:

What parameters does it need and what are you passing?

Then look at this and what StringBuffer needs - do these match?

4
votes

Two corrections:

import java.io.*;

To import everything in java.io.

And:

printBackwards(args);

To pass args to your printBackwards method (you declared it correctly, but didn't pass the variable).

2
votes

The method printBackwards takes a String[] as an argument, but you're not passing anything when you call it.

2
votes

This compiles :

public class HW1A {

    public static void main (String[] args) {
     printBackwards(args);
    }

    public static void printBackwards (String[] args) {
     StringBuffer backwards = new StringBuffer(args[0]);
     System.out.println(backwards.reverse());
    }

}

But you have to decide if the argument to pass to create the StringBuffer is the first element of the args array.

2
votes

No compilation error... but not sure this is what you want to do...

public class HW1A {
      public static void main (String[] args) {
         printBackwards(args);
      }

      public static void printBackwards (String[] args) {
         StringBuffer backwards = new StringBuffer();
         for (int i = 0; i < args.length; i++) {
             backwards.append(args[i]);
         }
         System.out.println(backwards.reverse());
      }
}

Parameters: Hello world!

Output: !dlrowolleH