如何将int转换为String?

时间:2011-01-30 06:39:54

标签: java string

我有一个int变量,当我将此变量设置为Android TextView的文本时,它会抛出一个错误,可能是因为它是一个Int。我已经检查但是找不到int的toString函数。那我怎么能这样做呢?

int sdRate=5;
//text_Rate is a TextView
text_Rate.setText(sdRate); //gives error

6 个答案:

答案 0 :(得分:96)

使用String.valueOf()

int sdRate=5;
//text_Rate is a TextView
text_Rate.setText(String.valueOf(sdRate)); //no more errors

答案 1 :(得分:13)

使用Integer类'静态toString()方法。

int sdRate=5;
text_Rate.setText(Integer.toString(sdRate));

答案 2 :(得分:4)

您可以使用

text_Rate.setText(""+sdRate);

答案 3 :(得分:2)

你有没有尝试过:

text_Rate.setText(String.valueOf(sdRate));

答案 4 :(得分:1)

您有两种选择:

1)使用String.valueOf()方法:

int sdRate=5;
text_Rate.setText(String.valueOf(sdRate));  //faster!, recommended! :)

2)添加一个空字符串:

int sdRate=5;
text_Rate.setText("" + sdRate)); 

投射不是一种选择,会抛出ClassCastException

int sdRate=5;
text_Rate.setText(String.valueOf((String)sdRate)); //EXCEPTION!

答案 5 :(得分:0)

可能你应该尝试这样

int sdRate=5;
//text_Rate is a TextView
text_Rate.setText(sdRate+""); //gives error
相关问题