如何进行一行文本并删除括号中的所有注释,空行,多余的空格和信息?

问题描述 投票:0回答:1

此项目要求我通过删除括号中的所有注释,空行,多余的空格和信息来读取正在处理的文件,然后将其打印到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;

    }

}

这里是总数:

// 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
java printwriter
1个回答
0
投票

您可以使用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");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.