问题
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.
回答6:
Better:
String itemId = String.valueOf(item.getId());
来源:https://stackoverflow.com/questions/9961892/cannot-invoke-tostring-on-the-primitive-type-int