我正在编写一个程序来检查这些{[(“和/ *符号是否与}}平衡)” /。让我感到困扰的是,我处理评论/ /部分的逻辑似乎不起作用。如何使该程序忽略/* */
(注释块)中的任何内容? 我已经尝试过indexOf(/ )方法并且它对我不起作用所以请不要将其称为重复。具体来说,是否有使用boolean来处理这个问题的方法吗?
这是我的评论逻辑:
if(ch == '{'||ch =='(' || ch=='['){
if(notinComment == true){
ms.push(ch);
notinComment = false;
}
notinComment = true;
}
这是我的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class SymbolBalance {
public static void main(String[] args){
if(args.length>0){
try{
Scanner input = new Scanner(new File (args[0]));
MyStack<Character> ms = new MyStack<>();
boolean quoteStart = true;
boolean notinComment = true;
char ch;
loop: while(input.hasNext()){
String str = input.next();
for(int i=0; i<str.length();i++){
ch = str.charAt(i);
//ignore the comment logic
if(ch == '{'||ch =='(' || ch=='['){
if(notinComment == true){
ms.push(ch);
notinComment = false;
}
notinComment = true;
}
else if(ch == '/' && i<str.length()-1 && str.charAt(i+1) == '*'){
ms.push(str.charAt(i+1));
}
else if (ch==')'){
if(ms.isEmpty()||ms.pop()!= '('){
System.out.println(") is mismatched");
break loop;
}
}
else if(ch == ']'){
if(ms.isEmpty() || ms.pop() != '['){
System.out.println("] is mismatched");
break loop;
}
}
else if(ch == '}'){
if(ms.isEmpty() || ms.pop() != '{'){
System.out.println("} is mismatched");
break loop;
}
}
else if(ch == '*' && i<str.length() -1 && str.charAt(i+1) == '/'){
if(ms.isEmpty() || ms.pop() != '*'){
System.out.println("*/ is mismatched");
break loop;
}
}
else if(ch == '"'){
if(quoteStart == true) {
ms.push(ch);
quoteStart = false;
}
else {
if(ms.isEmpty() || ms.pop() != '"'){
System.out.println(" \" is mismatched");
break loop;
}
quoteStart = true;
}
} //end of else
}//end fof while
}//end of while
input.close();
}//end of try
catch(FileNotFoundException e){
System.out.println("Cannot find file");
}//end of catch
}//end of if
else{
System.out.println("No command line argument");
}
}
}
这里是一个我们需要检查的示例输入文件:
/* this is to test whether the program can deal with an imbalance of { */
public class Test2 {
public static void main(String[] args) {
boolean haveYouWatchedHamiltonYet = true;
int theSchuylerSisters = 3;
int alexanderhamilton = 1;
int aaronburr = 1;
boolean amIinTheRoom = theRoomWhereItHappens();
/* imbalanced { test */
{
}
/*just a general comment */
public boolean theRoomWhereItHappens() {
boolean intheRoomWhereItHappens = false;
boolean isHappyAboutThis = false;
return intheRoomWhereItHappens && isHappyAboutThis;
}
}