[英]How can I change an int to a String for this object?
I'm learning Java here, and using a "GLabel" object. 我在这里学习Java,并使用“ GLabel”对象。 It's in the ACM Graphics library, and you can read about it here:
它在ACM图形库中,您可以在这里阅读有关它的信息:
http://jtf.acm.org/javadoc/student/acm/graphics/GLabel.html http://jtf.acm.org/javadoc/student/acm/graphics/GLabel.html
In short, the GLabel prints a string. 简而言之,GLabel打印一个字符串。 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. 这是我拥有的循环,但是由于存在int,因此无法编译。
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);
当我尝试这样做时:
GLabel( (String)k);
I get a "Cannot cast from int to String" error... 我收到“无法从int转换为String”错误...
EDIT: I have seen the setLabel method-maybe that is the only way to do this? 编辑:我已经看到了setLabel方法-也许这是唯一的方法吗?
Try GLabel("" + k);
试试
GLabel("" + k);
instead. 代替。
You can't cast an int
to a String
, so you have to do a conversion instead. 您不能将
int
转换为String
,因此必须进行转换。 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"
Integer.toString(k)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.