我的“匹配分隔符”Java代码遇到了问题。
首先,我需要有关字符计数器的帮助。一些朋友建议使用行计数器,我不知道在我的代码中使用哪个或者如何准确地实现它们。
其次,我应该做多行注释“/ * .... * /。我理解逻辑
*
*
/
但如果没有我的工作台,我似乎无法找到如何做到这一点。有什么帮助吗?
这是我的代码:
private Stack<Character> parenthesisStack = new Stack<Character>();
private Stack<Character> braceStack = new Stack<Character>();
private Stack<Character> bracketStack = new Stack<Character>();
private Stack<Character> slashStack = new Stack<Character>();
public void Match(String input) {
for (int j = 0; j < input.length(); j++) {
char currentGroupingSymbol = input.charAt(j);
switch (currentGroupingSymbol) {
case '(':
parenthesisStack.push(currentGroupingSymbol);
break;
case '[':
braceStack.push(currentGroupingSymbol);
break;
case '{':
bracketStack.push(currentGroupingSymbol);
break;
case ')':
if (!parenthesisStack.isEmpty()) {
if (currentGroupingSymbol == ')' && parenthesisStack.peek() == '(') {
System.out.println("The Parenthesis are Balanced");
parenthesisStack.pop();
}
} else {
System.out.println("Where is the matching parenthesis for " + currentGroupingSymbol + " at character " + j + "?");
}
break;
case ']':
if (!braceStack.isEmpty()) {
if (currentGroupingSymbol == ']' && braceStack.peek() == '[') {
System.out.println("The Braces are Balanced");
braceStack.pop();
}
} else {
System.out.println("Where is the matching brace for " + currentGroupingSymbol + " at character " + j + "?");
}
break;
case '}':
if (!bracketStack.isEmpty()) {
if (currentGroupingSymbol == '}' && bracketStack.peek() == '{') {
System.out.println("The Brackets are Balanced");
bracketStack.pop();
}
} else {
System.out.println("Where is the matching bracket for " + currentGroupingSymbol + " at character " + j + "?");
}
break;
case '/':
slashStack.push(currentGroupingSymbol);
if (input.charAt(j+1) == '/' ) {
System.out.println("Look at you with proper comments!");
} else {
System.out.println("Be careful! This " + currentGroupingSymbol + " could mean division! ");
}
}
}
if (!parenthesisStack.isEmpty()) {
System.out.println("You have one or more too many open Parenthesis");
}
if (!braceStack.isEmpty()) {
System.out.println("You have one or more too many open Braces");
}
if (!bracketStack.isEmpty()) {
System.out.println("You have one or more too many open Brackets");
}
}
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a file name");
String fileName = scan.nextLine();
File testFile = new File(fileName);
BufferedReader in = new BufferedReader(new FileReader(testFile));
String input = new String();
StringBuilder build = new StringBuilder();
while ((input = in.readLine()) != null) {
build.append(input);
}
Match prog = new Match();
prog.Match(build.toString());
}