[关闭]
@zsh-o 2018-07-05T16:53:40.000000Z 字数 1994 阅读 1819

删除Java文件中的所有注释(自动机解法)

算法


这个任务是要删除java文件中所有的注释,采取的方法为构建自动机判断当前字符是否应该删除,自动机图示如下,需要注意的是程序里面的字符串的内容会有影响例如包含", //等,要点是要判断正确,要涉及到所有情况
自动机
转换成代码如下

  1. //import java.util.Scanner;
  2. import java.io.File;
  3. import java.io.FileWriter;
  4. import java.io.BufferedReader;
  5. import java.io.FileReader;
  6. import java.io.PrintWriter;
  7. //import java.io.FileNotFoundException;
  8. import java.io.IOException;
  9. public class CommentRemoval {
  10. public static void main(String[] args){
  11. String inpath = "E:/workstation/github/Computer_Algorithms/OJs/others/SampleClass.java";
  12. String outpath = inpath.substring(0, inpath.length() - 4) + "txt";
  13. try{
  14. File infile = new File(inpath);
  15. File outfile = new File(outpath);
  16. if(infile.isFile() && infile.exists()){
  17. BufferedReader bufferedReader = new BufferedReader(new FileReader(infile));
  18. PrintWriter bufferedWriter = new PrintWriter(new FileWriter(outfile));
  19. char c;
  20. int i;
  21. while((i = bufferedReader.read()) != -1){
  22. // state 0
  23. c = (char)i;
  24. if(c == '/'){ // state 3
  25. i = bufferedReader.read();
  26. c = (char)i;
  27. if(c == '*'){ // state 4
  28. while((i = bufferedReader.read()) != -1){
  29. c = (char) i;
  30. if(c == '*'){ // state 6
  31. i = bufferedReader.read();
  32. c = (char)i;
  33. if(c == '/'){
  34. break;
  35. }else{
  36. continue;
  37. }
  38. }else{
  39. continue;
  40. }
  41. }
  42. }else if(c == '/'){ // state 5
  43. while((i = bufferedReader.read()) != -1){
  44. c = (char)i;
  45. if(c == '\n'){
  46. bufferedWriter.print(c);
  47. break;
  48. }else{
  49. continue;
  50. }
  51. }
  52. }else{
  53. bufferedWriter.print("/" + c);
  54. continue;
  55. }
  56. }else if(c == '"'){ // state 1
  57. bufferedWriter.print(c);
  58. while((i = bufferedReader.read()) != -1){
  59. c = (char)i;
  60. bufferedWriter.print(c);
  61. if(c == '\\'){ // state 2
  62. if((i = bufferedReader.read()) != -1){
  63. c = (char)i;
  64. bufferedWriter.print(c);
  65. if(c == '"'){
  66. continue;
  67. }
  68. }
  69. }else if(c == '"'){
  70. break;
  71. }
  72. }
  73. }else{
  74. bufferedWriter.print(c);
  75. }
  76. }
  77. bufferedWriter.close();
  78. bufferedReader.close();
  79. }
  80. } catch (IOException e) {
  81. e.printStackTrace();
  82. }
  83. }
  84. }

结果:

  1. /* Comment: This is a sample class for testing comment
  2. removal.
  3. Jianzhong Qi, 01 May 2016
  4. */
  5. /*
  6. * //fff
  7. * "fffff"
  8. */
  9. import java.util.Scanner;
  10. public class SampleClass{
  11. public static void main(String[] args) {
  12. // Print a "fff" message
  13. System.out.print("Hello // stude\"nts."); // haha /* haha
  14. }
  15. }
  1. import java.util.Scanner;
  2. public class SampleClass{
  3. public static void main(String[] args) {
  4. System.out.print("Hello // stude\"nts.");
  5. }
  6. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注