开发者

Incredibly simple android java question

开发者 https://www.devze.com 2023-01-29 02:49 出处:网络
How can I convert the below int to display the result of the sum as text in a textview? Am getting \'cannot invoke toString() on primitive type int\' - thought that was the point of toString!?!

How can I convert the below int to display the result of the sum as text in a textview?

Am getting 'cannot invoke toString() on primitive type int' - thought that was the point of toString!?!

public void onClick(View v) {
    // TODO Auto-generated method stub
    txtAnswer = (TextView)findViewById(R.id.txtAnswer);
    editStones 开发者_如何学运维= (EditText)findViewById(R.id.editStones);

    int result = 10 + 10;
    txtAnswer.setText(result.toString());
}


txtAnswer.setText(String.valueOf(result));

or this works also:

txtAnswer.setText("result is : "+result);


Use String.valueOf(result)


int is a primitive type in Java, meaning it is not a class, and therefore has no toString() method. You can use the Integer class or just use String.valueOf(result).


One of the more annoying things about java is that they still have primitives. So you have to use a Static Method of another class, either String.valueOf() or Integer.toString().


You can convert it using many formats as follows-

  1. Convert using Integer.toString(int)

    int number = -782;
    String numberAsString = Integer.toString(number);
    
  2. Convert using String.valueof(int)

    String.valueOf(number);
    
  3. Convert using Integer(int).toString()

    String numberAsString = new Integer(number).toString();
    
  4. Convert using String.format()

    String numberAsString = String.format ("%d", number);
    
0

精彩评论

暂无评论...
验证码 换一张
取 消