58 lines
2.1 KiB
JavaScript
58 lines
2.1 KiB
JavaScript
function checkJavaSyntax(code) {
|
|
let errors = [];
|
|
let lines = code.split("\n");
|
|
let openBraces = 0;
|
|
|
|
if (!code.match(/public\s+class\s+\w+\s*\{/)) {
|
|
errors.push("Error: Missing or incorrect class definition.");
|
|
}
|
|
|
|
if (!code.match(/public\s+static\s+void\s+main\s*\(String\[\]\s+args\)\s*\{/)) {
|
|
errors.push("Error: Missing or incorrect main method.");
|
|
}
|
|
|
|
let keywords = ["if", "else", "while", "for", "return", "int", "char", "float", "double", "void", "public", "static", "class"];
|
|
|
|
for (let i = 0; i < lines.length; i++) {
|
|
let line = lines[i].trim();
|
|
if (!line) continue;
|
|
|
|
if (line.includes("{")) openBraces++;
|
|
if (line.includes("}")) openBraces--;
|
|
|
|
let words = line.split(/\s+/);
|
|
for (let word of words) {
|
|
if (keywords.includes(word)) continue;
|
|
if (word.match(/^(if|else|while|for|return|public|static|class)$/i)) {
|
|
errors.push(`Error on line ${i + 1}: Misspelled keyword '${word}'. Did you mean '${word.toLowerCase()}'?`);
|
|
}
|
|
}
|
|
|
|
if (line.includes("x-;")) {
|
|
errors.push(`Error on line ${i + 1}: Incorrect operator 'x-;'. Did you mean 'x--;'?`);
|
|
}
|
|
|
|
if (!line.endsWith(";") && !line.includes("{") && !line.includes("}")) {
|
|
errors.push(`Error on line ${i + 1}: Missing semicolon.`);
|
|
}
|
|
|
|
if (line.includes("System.out.println") && !line.match(/System\.out\.println\(["'].*["']\)\s*;/)) {
|
|
errors.push(`Error on line ${i + 1}: Incorrect System.out.println syntax.`);
|
|
}
|
|
|
|
if (line.includes("System.out.pritln")) {
|
|
errors.push(`Error on line ${i + 1}: Misspelled 'System.out.println'. Did you mean 'System.out.println'?`);
|
|
}
|
|
|
|
if (line.includes('System.out.println("Done)')) {
|
|
errors.push(`Error on line ${i + 1}: Missing closing quote in System.out.println.`);
|
|
}
|
|
}
|
|
|
|
if (openBraces !== 0) {
|
|
errors.push("Error: Mismatched braces `{}`.");
|
|
}
|
|
|
|
return errors.length ? errors : ["Syntax is correct!"];
|
|
}
|