【问题标题】:Assigning value to variable within multiple while loops在多个while循环中为变量赋值
【发布时间】:2015-08-19 11:08:01
【问题描述】:

我有一段代码正在搜索 JSON 文件以查找匹配项,一旦找到匹配项,它会将 JSON 文件中的关联值分配给变量 currentLocation。我要问的问题是如何将此值分配给currentLocation 并在while 循环之外访问它?

代码块:

String currentLocation = null;
try {
  JsonReader jsonReader = new JsonReader(new FileReader("src/resources/objectLocation.json"));
  jsonReader.beginObject();
  while (jsonReader.hasNext()) {
    String nameRoot = jsonReader.nextName();
    if (nameRoot.equals("locations")) {
      jsonReader.beginObject();
      while (jsonReader.hasNext()) {
        String name = jsonReader.nextName();
          jsonReader.beginObject();
          while (jsonReader.hasNext()) {
            String n = jsonReader.nextName();
            n = jsonReader.nextString();
            if (n.equals(currentObject)) {
              currentLocation = name;
            }
          }
          jsonReader.endObject();
      }
      jsonReader.endObject();
    }
  }
  jsonReader.endObject();
  jsonReader.close();
}
catch (Exception e) {
}
return currentLocation + " " + currentObject;

据我了解,正在发生的事情是我正在寻找的值被分配给currentLocation OK,但随后它超出了我试图访问它的范围,因此返回 null。

我尝试将其声明为:

final String currentLocation;

然后给我错误variable currentLocation might be assigned in a loop,当然是。

我如何在我的 return 语句的 while 循环中访问 currentLocation 的值?

【问题讨论】:

  • 为什么不将currentLocation = name 替换为return name+" "+currentObject(将jsonReader.close() 移至finally 块)?
  • 您是否考虑过您的代码可能引发异常的可能性?因此,您将 currentLocation 设为 null?
  • 我给currentLocation分配了一个假值,并成功返回。
  • @TagirValeev 如果我这样做,我的代码会在 catch 块之后抱怨缺少 return。有没有办法解决这个问题?
  • @Colin747,当您的解析失败或没有找到(可能为空?)时,只需返回适当的内容。如果您认为这种情况永远不会发生,只需将throw new InternalError(); 放在最后一行即可。

标签: java json variables while-loop scope


【解决方案1】:

它可能会抛出异常,请检查您的 catch 块。如果没有异常,它应该返回更新后的 currentLocation 值。

【讨论】:

    猜你喜欢
    • 2011-07-12
    • 1970-01-01
    • 2019-06-09
    • 2016-01-13
    • 2013-11-15
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 2013-09-25
    相关资源
    最近更新 更多