0

So basically I want to do the following:

   String s1 = "hello";

   for(int count = s1.length() -1; count >= 0; count--){
        System.out.printf("%c, ", s1.charAt(count));
    }

but do that in a label instead. How can I format a label like printf? Using setTextf does not woek as seen below:

String s1 = "hello";
for(int count = s1.length() -1; count >= 0; count--){
        label1.setTextf("%c, ", s1.charAt(count));
    }
Forrest
  • 157
  • 14
  • `Label` does not have a `setTextf()` method. A good idea would be to read the official API docs for [Label](https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Label.html) so you have a better idea of what you should expect it to do. – Zephyr Mar 16 '19 at 22:44

1 Answers1

2

The printf() method is intended specifically for printing a formatted String to your output console.

If you want to format a String for other purposes, you need to use the String.format() method:

String s1 = "hello";
for(int count = s1.length() -1; count >= 0; count--){
    label1.setText(String.format("%c, ", s1.charAt(count)));
}

However, doing this within a loop as you are trying to do will result in a single char as your final Label text, since each call to setText() will overwrite the previous one.

Instead, you should build your final String using a 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());
Zephyr
  • 9,885
  • 4
  • 28
  • 63