gpt4 book ai didi

java - 有没有办法用方法初始化静态字段?

转载 作者:行者123 更新时间:2023-11-30 05:32:10 26 4
gpt4 key购买 nike

如何使用方法初始化类中的字符串数组?

private static String[] strNrs2 = 
{"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};

private static String[] colo = arr();


private String[] arr(){
String[] str99 = new String[strNrs2.length];
for (int i = 0; i<strNrs2.length;i++){
str99[i]= new StringBuilder(strNrs2[i]).reverse().toString();

}
return str99;
}

我想要这个:

private static String[] strNrs2 = 
{"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};

看起来像这样:

 private static String[] strNrs = 
{"oreZ","enO","owT","eerhT","ruoF","eviF","xiS","neveS","thgiE","eniN"};

但我只想做一次。因为我计划循环使用数组的方法一百万次。因此,它将大大降低我的运行速度。

完整代码:

  public class IntToStr {
private static String[] strNrs2 = {"Zero","One","Two","Three","Four","Five","Six",
"Seven","Eight","Nine"};

public static String intToStr(int nr) {

StringBuilder str = new StringBuilder("");

while (nr>0) {
int pop = nr%10;
nr= nr/10;
str.append(new StringBuilder(strNrs2[pop]).reverse().toString());
//By using this str.append(strNrs[pop]); runtime will increase considerably.

}
return str.reverse().toString();
}

public static void main(String[] args) {

for (int i = 0; i<10000000;i++)
intToStr(5555555);
System.out.println("Finished");

}



}

最佳答案

以下数组初始化:

private static String[] colo = arr();

不起作用,因为arr()是一个非静态方法,因此不能在初始化static变量的静态上下文中调用它。

您必须将 arr() 设为 static 方法,才能使 static 数组初始化工作:

private static String[] arr() {
...
}

关于java - 有没有办法用方法初始化静态字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57308336/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com