I'm learning Java here, and using a "GLabel" object. It's in the ACM Graphics library, and you can read about it here:
http://jtf.acm.org/javadoc/student/acm/graphics/GLabel.html
In short, the GLabel prints a st开发者_如何学运维ring. The thing is I have an int that I want to print there. How would I achieve this?
This is the loop I have, but this won't compile because of the int there.
for( int k = 1; i> 5; k++){
GLabel counter = new GLabel(k);
add(counter, (getWidth() / 2), (getHeight() / 2) );
pause (500);
remove(counter);
}
When I try this: GLabel( (String)k);
I get a "Cannot cast from int to String" error...
EDIT: I have seen the setLabel method-maybe that is the only way to do this?
Try GLabel("" + k);
instead.
You can't cast an int
to a String
, so you have to do a conversion instead. There are various ways to do this, but an easy way is to just append it to an empty string.
Other ways:
String.valueOf(k)
Integer.toString(k)
String.format("%d", k)
One caveat with using the +
string concatenation "trick" is that you need to take operator precedence into account.
System.out.println("" + 1 + 2); // this prints "12"
System.out.println("" + (1 + 2)); // this prints "3"
Integer.toString(k)
精彩评论