将参数附加到String

时间:2014-12-07 21:56:42

标签: java loops while-loop arguments stringbuilder

我需要编写一个简单的Java程序,以便逐步执行给定的字符串(从args []给出),并在遇到某个字符(例如' ^')时接收println:

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.");
    }
}   

1 个答案:

答案 0 :(得分:2)

您正在循环的每次迭代中创建new StringBuffer。您应该使用StringBuilder。你需要从args.length - 1开始。最后>= 0喜欢,

StringBuilder copyFromMe = new StringBuilder();
for (int j = args.length - 1; j>=0; j--) {
  // copyFromMe = new StringBuffer();
  copyFromMe.append(args[j]);
}