-1

I am writing a program to detect basic syntax errors in "code", I have a string that split up into lines and store it in an Array, I then check if each lines ends with one of the appropriate symbols using the .endsWith() function, below is my code:

public static void main (String[]args)
{
    String test = "public class < Hello>=World {\n" +
            " public static void-*//-- main(String[] args) {\n" +
            " // to pr&&int out+8+*+ hello world\n" +
            " System.out.pr < = in||tln(\"Hello World!\");\n" +
            " }\n" +
            "}\n";

    String lines[] = test.split("\\r?\\n");
    int lineIndex = 0;


    for (String line: lines)
    {
        lineIndex++;

        if (!line.endsWith(";") ||
        !line.endsWith("}"))
        {
            System.out.println("Line: " + lineIndex + " Invalid ending: " + line.charAt(line.length()-1));
        }

        else
        {
            System.out.println("Correct");
        }

    }
}

This is my current output:

Line: 1 Invalid ending: {
Line: 2 Invalid ending: {
Line: 3 Invalid ending: d
Line: 4 Invalid ending: ;
Line: 5 Invalid ending: }
Line: 6 Invalid ending: }

Shouldn't the program return "Correct" for lines 4,5,6 since it ends with one of the key symbols? Could this be an issue with the \n in the strings?

Thanks in advance for any help.

Quasease
  • 51
  • 4

1 Answers1

3

Your condition in the if statement is not correct.

Try this:

if (!line.endsWith(";") && !line.endsWith("}")