Cannot invoke toString() on the primitive type int

后端 未结 6 1901
谎友^
谎友^ 2021-02-07 11:31

Basically, what I\'m trying to do, is get the item ID, and set a price from a ini, basically like: itemid:price but, i cannot simply do item.getId().toString(). I\'m trying to g

相关标签:
6条回答
  • 2021-02-07 12:06
    String itemId = Integer.toString(item.getId());
    
    0 讨论(0)
  • 2021-02-07 12:09

    Primitive types (int, double, byte etc..) can't have methods. So use this :

    String itemId = String.valueOf(item.getId());
    
    0 讨论(0)
  • 2021-02-07 12:15

    Better:

    String itemId = String.valueOf(item.getId());
    
    0 讨论(0)
  • 2021-02-07 12:23

    Primitive types do not have methods, as they are not objects in Java. You should use the matching class:

    Integer.toString(item.getId());
    
    0 讨论(0)
  • 2021-02-07 12:23
    String itemId = Integer.toString(item.getId());
    
    0 讨论(0)
  • 2021-02-07 12:27

    Another simple way is to just say "" + myInt, assuming myInt is assigned.

    So try:

    item.getDefinitions().setValue("" + Integer.parseInt(split[1]));
    

    Of course, you may want to wrap the line in a try/catch in case there are parsing errors or split[1] is null, index out of range, etc.

    Alternatively, the method Integer.valueOf(str) will return an Integer object (as opposed to a primitive) which will allow you to directly call the .toString() function.

    item.getDefinitions().setValue(Integer.valueOf(split[1]).toString());
    

    I particularly like .valueOf() because it caches many Integer objects.

    0 讨论(0)
提交回复
热议问题