Cannot invoke toString() on the primitive type int

匿名 (未验证) 提交于 2019-12-03 08:41:19

问题:

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 get item What can I do to make it a string?

public static void getBuyPrice(Item item) {     try {         String itemId = item.getId().toString();         BufferedReader br = new BufferedReader(new FileReader(new File(                 "./data/prices.ini")));         String line;         while ((line = br.readLine()) != null) {             if (line.equals(itemId)) {                 String[] split = line.split(":");                 item.getDefinitions().setValue(Integer.parseInt(split[1]));             }         }         br.close();     } catch (Throwable e) {         System.err.println(e);     } } 

That is my code, (of course I have the error at item.getId().toString()), What can I do to convert that to a string?

回答1:

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

Integer.toString(item.getId()); 


回答2:

String itemId = Integer.toString(item.getId()); 


回答3:

String itemId = Integer.toString(item.getId()); 


回答4:

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

String itemId = String.valueOf(item.getId()); 


回答5:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!