【问题标题】:error with representing single quote in the switch statement在 switch 语句中表示单引号时出错
【发布时间】:2011-09-17 20:57:20
【问题描述】:

我必须删除文件中的所有 cmets。引号内的注释分隔符应被视为文本,并且必须打印到屏幕上。 cmets 中的引号被视为其他 cmets,必须删除。

当涉及到单引号时,下面的 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);
        }
    }
  }

【问题讨论】:

标签: java quotes switch-statement


【解决方案1】:

您必须转义单引号。 用这个

case '\''

【讨论】:

    【解决方案2】:

    尝试以下方法: str = str.replaceAll("/.+/","");我不确定上下文,但想法是使用正则表达式而不是像您尝试的那样简化代码。

    【讨论】:

    • 我们应该使用“就像 dfa 或 nfa”的状态
    猜你喜欢
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 2021-11-28
    • 2013-06-21
    • 1970-01-01
    相关资源
    最近更新 更多