我不确定程序应该如何检测开始引号和结束引号,它已经可以用于其他类型的括号,但是我找不到找到识别任何类型的结束引号的解决方案。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Scanner;
import java.util.Stack;
public class Balanced {
public static void main(String[] args) throws IOException {
//ask the user for the file name
Scanner key = new Scanner(System.in);
System.out.println("File name:");
String fileName = key.nextLine();
File f = new File(fileName);
//create the reader object
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
//allowed set of parenthesis
String paranthesis = "(){}[]<>";
//string builder to get the string of parenthesis
StringBuilder paraString = new StringBuilder("");
int ch;
char c;
try{
//read the file and generate the string
while((ch = reader.read()) != -1){
c = (char)ch;
//System.out.print(c);
if(paranthesis.indexOf(c)!=-1){
paraString.append(c);
}
}
}
catch (Exception e){
System.out.println(e.getMessage());
}
//pass the string and file name to the checker method
checker(paraString.toString(),fileName+"Output.txt");
}
public static void checker(String paraString,String filename) throws IOException{
//crate new Stack
Stack<Character> stack = new Stack<>();
//status = 0 means sucess
int status = 0;
//create new file object
File f = new File(filename);
//writer object to write
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f)));
//loop through each character and check for the status
for (char ch: paraString.toCharArray()) {
if(ch == '(' || ch == '{' || ch == '<' || ch == '[' || ch == '\"' || ch == '\''){
stack.push(ch);
}
else {
char top = stack.peek();
if(ch == ')' && top != '('){
status = 1;
writer.write(ch + " expected\n");
writer.write( "<" + "(" + "> "+ "expected");
}
else if(ch == '}' && top!='{'){
status = 1;
writer.write(ch + " expected\n");
writer.write( "<" + "{" + "> "+ "expected");
}
else if(ch == ']' && top!='['){
status = 1;
writer.write(ch + " expected\n");
writer.write( "<" + "[" + "> "+ "expected");
}
else if(ch == '>' && top!='<'){
status = 1;
writer.write(ch + " expected\n");
writer.write( "<" + "<" + "> "+ "expected");
}
else if(ch == '"' && top!='"'){
status = 1;
writer.write(ch + " expected\n");
writer.write( "<" + "<" + "> "+ "expected");
}
else if(ch == '\'' && top!='\''){
status = 1;
writer.write(ch + " expected\n");
writer.write( "<" + "<" + "> "+ "expected");
}
}
//is status become 1 break out of the loop
if(status==1){
break;
}
}
//if status is 0 then write sucess message
if(status==0){
writer.write("File Successfully parsed.\n");
}
writer.close();
}
}
解析器应该能够识别是否缺少引号,我已经尝试过其他用于REGEX的方法,但是它们不起作用,并且希望以一种我可以理解的简单方式得到建议。