gpt4 book ai didi

java - 如何取出一行文本并取出所有注释、空行、多余的空格和括号中的信息?

转载 作者:行者123 更新时间:2023-12-01 20:23:26 26 4
gpt4 key购买 nike

这个项目要求我通过取出所有注释、空行、额外的空格和括号中的信息来读取处理中的文件,然后将其打印到output.txt中。我在处理数据和删除所有注释、空行、额外的空格和括号中的信息时遇到了麻烦。

这是我的代码:

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

最佳答案

您可以使用Regex Expression匹配您要取出的东西:

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() 函数评估 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.isEmpty()) { // if there is something inside of current Line it appends it to printwriter
pw.append(currentLine + "\n");
}
}

关于java - 如何取出一行文本并取出所有注释、空行、多余的空格和括号中的信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58925478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com