Java 如何获取一行文本并删除括号中的所有注释、空行、额外空格和信息?
这个项目要求我读取一个正在处理的文件,去掉括号中的所有注释、空行、额外空格和信息,然后将其打印到output.txt中。我在处理数据和删除括号中的所有注释、空行、额外空格和信息时遇到了问题 这是我的密码:Java 如何获取一行文本并删除括号中的所有注释、空行、额外空格和信息?,java,printwriter,Java,Printwriter,这个项目要求我读取一个正在处理的文件,去掉括号中的所有注释、空行、额外空格和信息,然后将其打印到output.txt中。我在处理数据和删除括号中的所有注释、空行、额外空格和信息时遇到了问题 这是我的密码: import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; /* * @author wrigh4d * Date: 11
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
/*
* @author wrigh4d
* Date: 11/7/19
* Description: Takes instruction from SumN and then prints it into output.txt
*/
public class InstructionExtractor {
public static void main(String[] args) throws FileNotFoundException {
//Sets up Scanner/Print Writer and declares variable
File myFile = new File("sumN.txt");
Scanner sc = new Scanner(myFile);
File outputFile = new File("output.txt");
PrintWriter pw = new PrintWriter(outputFile);
String currentLine = "";
//Sets up while loop to read in each line
while(sc.hasNextLine()) {
currentLine = sc.nextLine(); //Sets each line to currentLine
currentLine = processLine(currentLine); //Takes currentLine down to processLine
if(currentLine != "") { //if there is something inside of current Line it appends it to printwriter
pw.append(currentLine + "\n");
}
}
pw.flush(); //prints onto output.txt
}
public static String processLine(String currentLine) {
//Gets rid of whitespace inside of currentLine
String a = currentLine.replaceAll("\\s+","");
System.out.println(a);
return a;
}
}
这里是SumN:
// Adds 1+...+100.
//initialize variable i and sum
@i // i refers to some mem. location.
M=1 // i=1
@sum // sum refers to some mem. location.
M=0 // sum=0
//the loop to sum
(LOOP) //the LOOP label
@i
D=M // D=i
@100
D=D-A // D=i-100
@END
D;JGT // If (i-100)>0 goto END
@i
D=M // D=i
@sum
M=D+M // sum=sum+i
@i
M=M+1 // i=i+1
@LOOP
0;JMP // Goto LOOP
//Terminate the program
(END)
@END
0;JMP // Infinite loop
您可以使用a来匹配要取出的物品:
public static String processLine(String currentLine) {
// Gets rid of whitespace inside of currentLine
String a = currentLine.replaceAll("//.+|\\s|\\(.+", "");
System.out.println(a);
return a;
}
还可以使用isEmpty()函数而不是!=“”:
您基本上需要一个解析器。您可能可以使用
String.split()
和一些逻辑。您可以避免代码中的注释重复类似Object a=new Object();//创建名为a的新对象
那么,您遇到的具体问题是什么?您是否考虑过按字符操作而不是按令牌/行操作,如图所示?
// Sets up while loop to read in each line
while (sc.hasNextLine()) {
currentLine = sc.nextLine(); // Sets each line to currentLine
currentLine = processLine(currentLine); // Takes currentLine down to processLine
if (!currentLine.isEmpty()) { // if there is something inside of current Line it appends it to printwriter
pw.append(currentLine + "\n");
}
}