Skip to content
Advertisement

appending arguments to a String

I need to write a simple Java program so as to step through a given string (given from args[]), and receive a println once a certain character (e.g. ‘^’) is encountered. However, I cannot find why I cannot receive such println. Could you please check what is the stem of the error?

public class JavaApplication15 {

    public static void main(String[] args) {
        StringBuffer copyFromMe = null;
        for (int j = args.length; --j<=0; ) {
            copyFromMe = new StringBuffer();
            copyFromMe.append(args[j]);
        } 

        StringBuffer copyToMe = new StringBuffer();

        int i = 0;
        char c = copyFromMe.charAt(i);
        while (c != 'g') {
            copyToMe.append(c);
            c = copyFromMe.charAt(++i);
        }
        System.out.println(copyToMe);
    }

    private static String String(String[] args) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}   

Advertisement

Answer

You’re creating a new StringBuffer with every iteration of your loop. You should use a StringBuilder. And you need to start at args.length - 1. Finally >= 0 like ,

StringBuilder copyFromMe = new StringBuilder();
for (int j = args.length - 1; j>=0; j--) {
  // copyFromMe = new StringBuffer();
  copyFromMe.append(args[j]);
} 
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement