tags:

views:

61

answers:

2

Hi folks, 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 string. 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?

+2  A: 

Integer.toString(k)

joeforker
+4  A: 

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:

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"
polygenelubricants
That worked! I had tried GLabel( + k +); with no success but hadn't thought about that. Thanks!
Joel
Using `("" + k)` => horrible! `String.valueOf(k)` is your friend.
dimitko