Stuck on String literals #UE7 : JAVA

I’m stuck on Stage #ue7.

I’ve tried possible solution

Here are my logs:

remote: [tester::#UE7] Running tests for Stage #UE7 (Scanning: String literals)
remote: [tester::#UE7] [test-1] Running test case: 1
remote: [tester::#UE7] [test-1] Writing contents to ./test.lox:
remote: [tester::#UE7] [test-1] [test.lox] "hello"
remote: [tester::#UE7] [test-1] $ ./your_program.sh tokenize test.lox
remote: [your_program] Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Range [1, 0) out of bounds for length 7
remote: [your_program]  at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:55)
remote: [your_program]  at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:52)
remote: [your_program]  at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:213)
remote: [your_program]  at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:210)
remote: [your_program]  at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:98)
remote: [your_program]  at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckFromToIndex(Preconditions.java:112
remote: [your_program]  at java.base/jdk.internal.util.Preconditions.checkFromToIndex(Preconditions.java:349)
remote: [your_program]  at java.base/java.lang.String.checkBoundsBeginEnd(String.java:4963)
remote: [your_program]  at java.base/java.lang.String.substring(String.java:2925)
remote: [your_program]  at Main.main(Main.java:113)
remote: [tester::#UE7] [test-1] expected exit code 0, got 1
remote: [tester::#UE7] [test-1] Test failed (try setting 'debug: true' in your codecrafters.yml to see more details)

And here’s a snippet of my code:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
  private static int lineNumber = 1;

  public static void main(String[] args) {

    if (args.length < 2) {
      System.err.println("Usage: ./your_program.sh tokenize <filename>");
      System.exit(1);
    }

    String command = args[0];
    String filename = args[1];

    boolean hasErrors = false;

    if (!command.equals("tokenize")) {
      System.err.println("Unknown command: " + command);
      System.exit(1);
    }

    String fileContents = "";
    try {
      fileContents = Files.readString(Path.of(filename));
    } catch (IOException e) {
      System.err.println("Error reading file: " + e.getMessage());
      System.exit(1);
    }

    if (fileContents.length() > 0) {
      for (int idx = 0; idx < fileContents.length(); idx++) {
        char c = fileContents.charAt(idx);

        // if (Character.isWhitespace(c)) continue; // Ignore whitespace characters
        // using Character Class
        if (c == ' ' || c == '\t')
          continue;

        // For every new line we will count number
        if (c == '\n') {
          ++lineNumber;
          continue;
        }

        switch (c) {
          case '(' -> System.out.println("LEFT_PAREN ( null");
          case ')' -> System.out.println("RIGHT_PAREN ) null");
          case '{' -> System.out.println("LEFT_BRACE { null");
          case '}' -> System.out.println("RIGHT_BRACE } null");
          case '.' -> System.out.println("DOT . null");
          case ',' -> System.out.println("COMMA , null");
          case ';' -> System.out.println("SEMICOLON ; null");
          case '+' -> System.out.println("PLUS + null");
          case '-' -> System.out.println("MINUS - null");
          case '*' -> System.out.println("STAR * null");
          case '=' -> {
            if (idx + 1 < fileContents.length() && fileContents.charAt(idx + 1) == '=') {
              System.out.println("EQUAL_EQUAL == null");
              ++idx;
            } else {
              System.out.println("EQUAL = null");
            }
          }
          case '!' -> {
            if (idx + 1 < fileContents.length() && fileContents.charAt(idx + 1) == '=') {
              System.out.println("BANG_EQUAL != null");
              ++idx;
            } else {
              System.out.println("BANG ! null");
            }
          }
          case '<' -> {
            if (idx + 1 < fileContents.length() && fileContents.charAt(idx + 1) == '=') {
              System.out.println("LESS_EQUAL <= null");
              ++idx;
            } else {
              System.out.println("LESS < null");
            }
          }
          case '>' -> {
            if (idx + 1 < fileContents.length() && fileContents.charAt(idx + 1) == '=') {
              System.out.println("GREATER_EQUAL >= null");
              ++idx;
            } else {
              System.out.println("GREATER > null");
            }
          }
          case '/' -> {
            if (idx + 1 < fileContents.length() && fileContents.charAt(idx + 1) == '/') {
              while (idx < fileContents.length() && fileContents.charAt(idx) != '\n') {
                idx++;
              }
              ++lineNumber;
            } else {
              System.out.println("SLASH / null");
            }
          }

          case '"' -> {
            int startIdx = idx;
            while (idx < fileContents.length() && fileContents.charAt(idx) != '"') {
              if (fileContents.charAt(idx) == '\n') ++lineNumber;
              ++idx;
            }
            if (fileContents.charAt(idx) != '"') {
              System.err.println("[line " + lineNumber + "] Error: Unterminated string.");
              hasErrors = true;
            }
            else{
              System.out.println("STRING \"" + fileContents.substring(startIdx + 1, idx) + "\" "+fileContents.substring(startIdx + 1, idx));
            }
          }

          default -> {
            System.err.println("[line " + lineNumber + "] Error: Unexpected character: " + c);
            hasErrors = true;
          }
        }
      }
    }
    System.out.println("EOF  null");

    if (hasErrors) {
      System.exit(65);
    } else {
      System.exit(0);
    }
  }
}

Hi @debabrata2050, if you can push your latest change to your github repo Lox/codecrafters-interpreter-java/src/main/java/Main.class at main · debabrata2050/Lox, I’ll get back to you before the end of the week.

I’ve solved the issue

Here is my code

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
  private static int lineNumber = 1;

  public static void main(String[] args) {

    if (args.length < 2) {
      System.err.println("Usage: ./your_program.sh tokenize <filename>");
      System.exit(1);
    }

    String command = args[0];
    String filename = args[1];

    boolean hasErrors = false;

    if (!command.equals("tokenize")) {
      System.err.println("Unknown command: " + command);
      System.exit(1);
    }

    String fileContents = "";
    try {
      fileContents = Files.readString(Path.of(filename));
    } catch (IOException e) {
      System.err.println("Error reading file: " + e.getMessage());
      System.exit(1);
    }

    if (fileContents.length() > 0) {
      for (int idx = 0; idx < fileContents.length(); idx++) {
        char c = fileContents.charAt(idx);

        // if (Character.isWhitespace(c)) continue; // Ignore whitespace characters
        // using Character Class
        if (c == ' ' || c == '\t')
          continue;

        // For every new line we will count number
        if (c == '\n') {
          ++lineNumber;
          continue;
        }

        switch (c) {
          case '(' -> System.out.println("LEFT_PAREN ( null");
          case ')' -> System.out.println("RIGHT_PAREN ) null");
          case '{' -> System.out.println("LEFT_BRACE { null");
          case '}' -> System.out.println("RIGHT_BRACE } null");
          case '.' -> System.out.println("DOT . null");
          case ',' -> System.out.println("COMMA , null");
          case ';' -> System.out.println("SEMICOLON ; null");
          case '+' -> System.out.println("PLUS + null");
          case '-' -> System.out.println("MINUS - null");
          case '*' -> System.out.println("STAR * null");
          case '=' -> {
            if (idx + 1 < fileContents.length() && fileContents.charAt(idx + 1) == '=') {
              System.out.println("EQUAL_EQUAL == null");
              ++idx;
            } else {
              System.out.println("EQUAL = null");
            }
          }
          case '!' -> {
            if (idx + 1 < fileContents.length() && fileContents.charAt(idx + 1) == '=') {
              System.out.println("BANG_EQUAL != null");
              ++idx;
            } else {
              System.out.println("BANG ! null");
            }
          }
          case '<' -> {
            if (idx + 1 < fileContents.length() && fileContents.charAt(idx + 1) == '=') {
              System.out.println("LESS_EQUAL <= null");
              ++idx;
            } else {
              System.out.println("LESS < null");
            }
          }
          case '>' -> {
            if (idx + 1 < fileContents.length() && fileContents.charAt(idx + 1) == '=') {
              System.out.println("GREATER_EQUAL >= null");
              ++idx;
            } else {
              System.out.println("GREATER > null");
            }
          }
          case '/' -> {
            if (idx + 1 < fileContents.length() && fileContents.charAt(idx + 1) == '/') {
              while (idx < fileContents.length() && fileContents.charAt(idx) != '\n') {
                idx++;
              }
              ++lineNumber;
            } else {
              System.out.println("SLASH / null");
            }
          }

          case '"' -> {
            int startIdx = idx;
            idx++;
            while (idx < fileContents.length() && fileContents.charAt(idx) != '"') {
              if (fileContents.charAt(idx) == '\n') {
                ++lineNumber;
              }
              ++idx;
            }
            if (idx >= fileContents.length()) {
              System.err.println("[line " + lineNumber + "] Error: Unterminated string.");
              hasErrors = true;
            } else {
              String lexeme = fileContents.substring(startIdx, idx + 1); // Include quotes
              String value = fileContents.substring(startIdx + 1, idx); // Exclude quotes
              System.out.println("STRING " + lexeme + " " + value);
            }
          }

          default -> {
            System.err.println("[line " + lineNumber + "] Error: Unexpected character: " + c);
            hasErrors = true;
          }
        }
      }
    }
    System.out.println("EOF  null");

    if (hasErrors) {
      System.exit(65);
    } else {
      System.exit(0);
    }
  }
}

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.