Rubenex
Rubenex

Reputation: 479

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

}

Upvotes: 2

Views: 84

Answers (3)

Amit.rk3
Amit.rk3

Reputation: 2417

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

Upvotes: 2

Codebender
Codebender

Reputation: 14448

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

Upvotes: 2

Florian Schaetz
Florian Schaetz

Reputation: 10662

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.

Upvotes: 1

Related Questions