【问题标题】:If within a loop not working as expected java如果在循环内没有按预期工作 java
【发布时间】:2015-07-31 10:14:25
【问题描述】:

我正在从文本文件(“text.txt”)中读取行,然后将它们存储到树形图中,直到出现“应用”一词。

但是执行此操作后,我在树形图中没有我想要的最后一行“4 apply”

文本.txt
1 个添加
3 乘法
4 申请
6 添加

Scanner input = new Scanner(file);
while(input.hasNextLine()){

    String line = input.nextLine();
    String[] divline = line.split(" ");

    TreeMap<Integer, String> Values = new TreeMap();

    if(!divline[1].equals("apply"))
    {
        Values.put(Integer.valueOf(divline[0]), divline[1]);    
    } 
    else
    {
        Values.put(Integer.valueOf(divline[0]), divline[1]);
        break;
    }

    System.out.println(Values);

}

【问题讨论】:

  • 没有“if循环”这样的东西。
  • 你可以把valores.put(Integer.valueOf(divline[0]), divline[1]);放在ìf之外

标签: java loops if-statement


【解决方案1】:

您每次都在 while 循环中创建新地图。在while循环之前放置以下代码。

TreeMap<Integer, String> valores = new TreeMap();

还需要更正地图内容的打印。所以你的最终代码可以是

Scanner input = new Scanner(file);
TreeMap<Integer, String> valores = new TreeMap();
     while(input.hasNextLine()){

        String line = input.nextLine();
        String[] divline = line.split(" ");           

        if(!divline[1].equals("apply")){
            valores.put(Integer.valueOf(divline[0]), divline[1]);   
        } else {
            valores.put(Integer.valueOf(divline[0]), divline[1]);
            break;
        }             

    }

for (Entry<Integer,String> entry: valores){
   System.out.println(entry.getKey() + "- "+entry.getValue());
}

【讨论】:

    【解决方案2】:

    4 apply 被添加到 valores 映射中,但它没有被打印,因为您在 print 语句之前跳出了循环。

    另外,您可能需要将 valores 映射的创建移到 while 循环之前。以及循环后的打印。

        TreeMap<Integer, String> valores = new TreeMap();
    
        while(input.hasNextLine()){
    
        String line = input.nextLine();
        String[] divline = line.split(" ");
    
        if(!divline[1].equals("apply")){
            valores.put(Integer.valueOf(divline[0]), divline[1]);   
        } else {
            valores.put(Integer.valueOf(divline[0]), divline[1]);
            break;
        }
        }
    
        System.out.println(valores);
    

    【讨论】:

      【解决方案3】:

      您正在为每一行创建一个新的“价值”TreeMap,然后打印包含该行的 TreeMap。在“应用”的情况下,您也可以这样做,创建一个新地图,将值放在那里 - 只有通过破坏,您才能跳过 System.out.println 部分。

      你需要把TreeMap的声明放在while前面。

      【讨论】:

        猜你喜欢
        • 2021-01-09
        • 2013-09-28
        • 1970-01-01
        • 2011-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多