2012-04-01 74 views
8

上调用toString()基本上,我试图做的是获取项目ID,并从ini设置价格,基本上如下所示:itemid:price 但是,我不能简单地做item.getId()。的toString()。 我想要获得物品 我能做些什么来使它成为一个字符串?无法在原始类型int

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()方法),我能做些什么将其转换成字符串?

+3

String itemID =“”+ item.getId(); – 2012-04-01 04:24:55

+0

对不起,这不是一个完整的答案(因为我没有足够的权限来评论),但你写的Item类的ID的toString()方法?或者只是使用Integer.toString(item.getId()如果ID是一个原始类型。 – 2012-04-01 04:25:09

回答

45

原始类型没有方法,因为它们不是在Java对象。您应该使用匹配的类:

Integer.toString(item.getId()); 
+0

感谢您解释它。 – 2012-04-01 04:30:39

6
String itemId = Integer.toString(item.getId()); 
+0

啊,是的,为什么我没有想到这首先!谢谢! – 2012-04-01 04:24:07

+0

@QuantumMechanic:你打败我 – 2012-04-01 04:24:25

-1

原始类型(int,双,字节等)不能有方法。 所以用这个:

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

另一种简单的方法是只说"" + myInt,假设敏分配。

所以尝试:

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

当然,你可能想换行线一个try/catch的情况下有解析错误或拆分[1]为空,指数超出范围,等等。

或者,Integer.valueOf(str)将返回整数对象(而不是原始的),这将允许直接调用的ToString()函数的方法。

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

我特别喜欢.valueOf(),因为它缓存了很多Integer对象。