[英]Cannot invoke toString() on the primitive type int
基本上,我正在嘗試做的是獲取商品ID,並從ini設置價格,基本上就像:itemid:price但是,我不能簡單地做item.getId()。toString()。 我正在嘗試獲取項目我該怎么做才能使它成為一個字符串?
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);
}
}
那是我的代碼,(當然我在item.getId()。toString()中有錯誤,我該怎么做才能將它轉換為字符串?
原始類型沒有方法,因為它們不是Java中的對象。 你應該使用匹配類:
Integer.toString(item.getId());
String itemId = Integer.toString(item.getId());
String itemId = Integer.toString(item.getId());
原始類型(int,double,byte等..)不能有方法。 所以使用這個:
String itemId = String.valueOf(item.getId());
另一個簡單的方法是只說"" + myInt
,假設分配了myInt。
所以嘗試:
item.getDefinitions().setValue("" + Integer.parseInt(split[1]));
當然,如果存在解析錯誤或者split [1]為null,索引超出范圍等,您可能希望將該行包裝在try / catch中。
或者, Integer.valueOf(str)
方法將返回一個Integer對象(而不是一個原語),它允許您直接調用.toString()函數。
item.getDefinitions().setValue(Integer.valueOf(split[1]).toString());
我特別喜歡.valueOf()因為它緩存了許多Integer對象。
更好:
String itemId = String.valueOf(item.getId());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.