我必须删除文件中的所有注释。引号内的注释分隔符应视为文本,并且必须打印到屏幕上。注释中的引号被视为其他注释,必须删除。
当涉及单引号时,我遇到以下switch语句的问题,它给了我一个错误。
我知道错误是什么,但我只是不知道如何解决它。
import java.io.*;
public class Q3{
public static final int STATE_NORMAL = 0;
public static final int STATE_QUOTE_SINGLE = 1; // this:''
public static final int STATE_QUOTE_DOUBLE = 5; // this: ""
public static final int STATE_SLASH = 2; // this: /
public static final int STATE_SLASH_STAR = 3; // this: /* *
public static final int STATE_COMMENT = 4; // this: /* */ || /* only
public static void main(String[] argv) throws IOException{
final int EOF = -1;
InputStreamReader in = new InputStreamReader(System.in);
int c;
char[] buffer = new char[2];
int currState = Q3.STATE_NORMAL;
char outChar;
while((c = in.read()) != EOF){
outChar = (char) c;
switch (outChar){
case '/' :
/* if(currState == Q3.STATE_QUOTES)
currState ==Q3.STATE_QUOTES; */
if(currState == Q3.STATE_NORMAL)
currState = Q3.STATE_SLASH;
else if(currState == Q3.STATE_COMMENT)
currState = Q3.STATE_NORMAL;
break;
case '*':
if(currState == Q3.STATE_SLASH)
currState = Q3.STATE_COMMENT;
break;
case '"':
if(currState == Q3.STATE_NORMAL)
currState = Q3.STATE_QUOTE_DOUBLE;
if(currState == Q3.STATE_QUOTE_DOUBLE)
currState = Q3.STATE_NORMAL;
break;
*case ''':
if(currState == Q3.STATE_NORMAL)
currState = Q3.STATE_QUOTE_SINGLE;
if(currState == Q3.STATE_QUOTE_SINGLE)
currState = Q3.STATE_NORMAL;
break;*
}
if(currState != Q3.STATE_COMMENT)
System.out.print(outChar);
}
}
}
答案 0 :(得分:4)
你必须逃避单引号。 使用这个
case '\''
答案 1 :(得分:0)
尝试以下方法: str = str.replaceAll(“/ 。+ /”,“”);我不确定上下文,但想法是使用正则表达式而不是像你正在尝试的简化代码。