Skip to content
Advertisement

Adding values to Map from a File

I want to iterate through a file that has key/value pairs and put them into a Map.

The file contains values like so:

forward 5
up 4
down 3
down 6
forward 4
...

Here is my code:

       private static void depthPosition() throws IOException {

        BufferedReader bufferedReader = new BufferedReader(new FileReader("/Users/WorkAcc/Desktop/file.txt"));
        String lines;
        Map<String, Integer> instructions = new HashMap<>();
        String [] pair;

        while ((lines = bufferedReader.readLine()) != null) {
           pair = lines.split(" ");
           instructions.put(pair[0], Integer.valueOf(pair[1]));
        }
        System.out.println(instructions);
    }
}

The problem I am having is that the Map called instructions is not adding new values from the file, it stops at size 3, not sure why. Would appreciate some help here. Thanks!

Advertisement

Answer

This is an example of how you can calculate what you indicate in the comments.

public void depthPosition() throws IOException {
    int value = 5;
    List<Instruction> instructions = readInstructionsFromFile("/Users/WorkAcc/Desktop/file.txt");
    int result = calculateDepthPosition(instructions, value);
    System.out.println("result is: "+result);
}

private List<Instruction> readInstructionsFromFile(String filePath) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
    String line;
    Instruction instruction;
    List<Instruction> instructions = new ArrayList<>();
    String[] pair;

    while ((line = bufferedReader.readLine()) != null) {
        pair = line.split(" ");
        instruction = new Instruction(pair[0], Integer.valueOf(pair[1]));
        instructions.add(instruction);
    }
    return instructions;
}

private int calculateDepthPosition(List<Instruction> instructions, int value){
    int nextValue = value;
    int result = value;
    for (Instruction instruction : instructions) {
        nextValue = instruction.apply(nextValue);
        result = Math.min(result, nextValue);
    }
    return result;
}

public static class Instruction {

    private String type;
    private int amount;

    public Instruction(String type, int amount) {
        this.type = type;
        this.amount = amount;
    }

    public int apply(int value) {
        switch (type) {
            case "forward":
                return value + amount;
            case "down":
                return value - amount;
            case "up":
                return value ?? amount;
            default:
                return value;
        }
    }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement