@zsh-o
2018-07-05T16:53:40.000000Z
字数 1994
阅读 1819
算法
这个任务是要删除java文件中所有的注释,采取的方法为构建自动机判断当前字符是否应该删除,自动机图示如下,需要注意的是程序里面的字符串的内容会有影响例如包含", //
等,要点是要判断正确,要涉及到所有情况
转换成代码如下
//import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;
//import java.io.FileNotFoundException;
import java.io.IOException;
public class CommentRemoval {
public static void main(String[] args){
String inpath = "E:/workstation/github/Computer_Algorithms/OJs/others/SampleClass.java";
String outpath = inpath.substring(0, inpath.length() - 4) + "txt";
try{
File infile = new File(inpath);
File outfile = new File(outpath);
if(infile.isFile() && infile.exists()){
BufferedReader bufferedReader = new BufferedReader(new FileReader(infile));
PrintWriter bufferedWriter = new PrintWriter(new FileWriter(outfile));
char c;
int i;
while((i = bufferedReader.read()) != -1){
// state 0
c = (char)i;
if(c == '/'){ // state 3
i = bufferedReader.read();
c = (char)i;
if(c == '*'){ // state 4
while((i = bufferedReader.read()) != -1){
c = (char) i;
if(c == '*'){ // state 6
i = bufferedReader.read();
c = (char)i;
if(c == '/'){
break;
}else{
continue;
}
}else{
continue;
}
}
}else if(c == '/'){ // state 5
while((i = bufferedReader.read()) != -1){
c = (char)i;
if(c == '\n'){
bufferedWriter.print(c);
break;
}else{
continue;
}
}
}else{
bufferedWriter.print("/" + c);
continue;
}
}else if(c == '"'){ // state 1
bufferedWriter.print(c);
while((i = bufferedReader.read()) != -1){
c = (char)i;
bufferedWriter.print(c);
if(c == '\\'){ // state 2
if((i = bufferedReader.read()) != -1){
c = (char)i;
bufferedWriter.print(c);
if(c == '"'){
continue;
}
}
}else if(c == '"'){
break;
}
}
}else{
bufferedWriter.print(c);
}
}
bufferedWriter.close();
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
结果:
/* Comment: This is a sample class for testing comment
removal.
Jianzhong Qi, 01 May 2016
*/
/*
* //fff
* "fffff"
*/
import java.util.Scanner;
public class SampleClass{
public static void main(String[] args) {
// Print a "fff" message
System.out.print("Hello // stude\"nts."); // haha /* haha
}
}
import java.util.Scanner;
public class SampleClass{
public static void main(String[] args) {
System.out.print("Hello // stude\"nts.");
}
}