这个问题在这里已有答案:
所以基本上我想做以下事情:
String s1 = "hello";
for(int count = s1.length() -1; count >= 0; count--){
System.out.printf("%c, ", s1.charAt(count));
}
但是在标签中这样做。如何格式化printf等标签?使用setTextf并不像下面所示:
String s1 = "hello";
for(int count = s1.length() -1; count >= 0; count--){
label1.setTextf("%c, ", s1.charAt(count));
}
printf()
方法专门用于将格式化的String
打印到输出控制台。
如果要将String
格式化为其他目的,则需要使用String.format()
方法:
String s1 = "hello";
for(int count = s1.length() -1; count >= 0; count--){
label1.setText(String.format("%c, ", s1.charAt(count)));
}
但是,在你尝试做的循环中执行此操作将导致单个char
作为最终的Label
文本,因为每次调用setText()
都将覆盖前一个。
相反,你应该使用String
构建你的最终StringBuilder
:
String s1 = "hello";
StringBuilder sb = new StringBuilder();
for(int count = s1.length() -1; count >= 0; count--){
sb.append(String.format("%c, ", s1.charAt(count)));
}
label1.setText(sb.toString());