类型不匹配:无法从元素类型Object转换为String错误

时间:2017-01-20 15:38:22

标签: java eclipse

所以我在以下代码中遇到错误:

for (final String key : keySet)

我不知道该怎么做,请帮忙。 :C 如果你回答那就太棒了

Config.log("Loading " + fileName);
final Properties props = new Properties();
   props.load(in);
   final Set keySet = props.keySet();
   // error here!
   for (final String key : keySet) {
       final String prefix = "width.";
       if (key.startsWith(prefix)) {
          final String numStr = key.substring(prefix.length());
          final int num = Config.parseInt(numStr, -1);
          if (num < 0 || num >= FontRenderer.charWidth.length) {
             continue;
          }
          final String value = props.getProperty(key);
          final float width = Config.parseFloat(value, -1.0f);
          if (width < 0.0f) {
             continue;
          }
      FontRenderer.charWidth[num] = width;

1 个答案:

答案 0 :(得分:0)

props.keySet()返回一组对象,你的for-loop认为它处理String类型的键。

您需要手动将密钥转换为String或使用toString():

Config.log("Loading " + fileName);
final Properties props = new Properties();
props.load(in);
final Set keySet = props.keySet();
for (final Object key : keySet) {
    final String prefix = "width.";
    if (key.toString().startsWith(prefix)) {
        final String numStr = key.toString().substring(prefix.length());
        final int num = Config.parseInt(numStr, -1);
        if (num < 0 || num >= FontRenderer.charWidth.length) {
            continue;
        }
        final String value = props.getProperty(key.toString());
        final float width = Config.parseFloat(value, -1.0f);
        if (width < 0.0f) {
            continue;
        }
        FontRenderer.charWidth[num] = width;
    }
}