简体   繁体   中英

If within a loop not working as expected java

I'm reading lines from a text file ("text.txt") and then storing them into a treemap, until the word apply appears.

However after performing this I don't have the last row "4 apply" I want in the treemap

text.txt
1 add
3 multiply
4 apply
6 add

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);

}

You are creating new map inside while loop every time. Put below code before while loop.

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

Also printing of map content needs to be corrected. So your final code can be

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());
}

4 apply is getting added to valores map, but it's not getting printed because you are breaking out of the loop before the print statement.

Also, you may need to move the creation of valores map before while loop. And the printing after the loop.

    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);

You are creating a new "valores" TreeMap for each line and then print that TreeMap that contains that one line. In the case of 'apply' you do the same, creating a new map, putting the value there - only by breaking, you skip the System.out.println part.

You need to put the declaration of the TreeMap before the while.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM