error with representing single quote in the switch statement
I have to remove all the comments in a file. Comment delimiters within quotes should be treated as text and must be printed to the screen. Quotes inside comments are treated as other comments and have to be removed.
I'm having a problem with the following switch statement when it comes to single quotes, it's giving me an error.
I know what the error is, but I just don't know how to fix it.
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);
}
}
}
You will have to escape the single quotes. use this
case '\''
Try the following: str = str.replaceAll("/.+/",""); I am not sure about the context, but the idea is to use Regular Expressions instead of a simplifies code like you're trying.
精彩评论