DEV Community

Cover image for Advent of Code 2021 - Day 2
Petra
Petra

Posted on

Advent of Code 2021 - Day 2

Hi Everyone!

My solution of the first puzzle of Day 2!

package main;

import java.io.File;
import java.util.*;

public class Puzzle {
  public static void main(String[] args) {
    try {
      File input = new File("/Users/files/input.txt");
      Scanner sc = new Scanner(input);
      int x = 0;
      int y = 0;
      while (sc.hasNextLine()) {
        String inputLine = sc.nextLine();
        int number = Integer.parseInt(inputLine.substring(inputLine.length() - 1));
        if (inputLine.contains("forward")) x += number;
        else if (inputLine.contains("down")) y += number;
        else y -= number;
      }
      System.out.println(x * y);

    } catch (Exception e) {
      System.out.println("Error!");
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)