我想用Stringbuilder创建一个long []数组,但是用这段代码我得到了“ java.lang.NumberFormatException:”。

protected long[] getpattern(int numbercount, int value) {
        StringBuilder longstringbuilder = new StringBuilder();

        while(numbercount > 0) {
            longstringbuilder.append("100, ");
            longstringbuilder.append(value + ", ");
            numbercount--;
        }
            longstringbuilder.append("100");

        String longstring = longstringbuilder.toString();

            long[] pattern = new long[] {Long.parseLong(longstring)};




        return pattern;

    }


我该如何解决?
谢谢你的回答

最佳答案

您知道数组中将有多少个元素:两次numbercount加1。因此,只需构建该数组即可:

long[] values = new long[2*numbercount+1];
for (int a = 0; a < numbercount; ++a) {
  values[2*a+0] = 100;
  values[2*a+1] = value;
}
values[values.length-1] = 100;


完全不需要涉及StringBuilder

09-11 17:22