java - 改变牙套的样式

标签 java arraylist file-io printwriter

你好,我想编写一个改变Java程序的程序 从下一行大括号样式到行尾大括号样式,如下所示

公开课测试

{

     public static void main(String [] args)

    {


    if (expr)

    {

    }
}

对此

public class Test {

    public static void main(String [] args) {

    if (expr) {

    }

}

程序应该从用户那里读入(用“输入文件名:”提示他们) 包含要更改的程序的文件的名称。如果该文件无法 打开后,向用户打印一条错误消息(“Bad filename”)并提示 再次输入文件名,修改后的文件应写回您读取的同一文件 从。您不能在打开文件的同时打开该文件进行读取 用于写作。所以你应该存储你想要写入文件的行 在字符串的 ArrayList 中,然后将它们写入文件 关闭用于读取文件的 Scanner 对象

这是我到目前为止所写的内容,但我遇到了错误。谁能帮忙, 谢谢

import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;

public class Extension {

    public static void main(String[] args){
      Scanner input = new Scanner(System.in);
      String fileName = "";
      System.out.println("Enter File Name: ");
      fileName = input.next();
      File f = new File("src/" + fileName);
      do{
       if(f.exists()){

               }
        else{
        System.out.println("Bad filename");
        System.out.println("Enter File Name: ");
        fileName = input.nextLine();
     }

    } while (!(f.exists()));

    ArrayList<String> fileRead = new ArrayList<String>();
    String paran = ("{");
    String newLine = "";
    while(input.hasNextLine()) {
    fileRead.add(input.nextLine());
   }
    input.close();
    f.close;
    //File f = new File("src/"+ fileName);

   PrintWriter output = new PrintWriter(f);
   output.print(fileRead.get(0)) ;
   for(int i = 1; i < fileRead.size()-1 ; i++){
      if(fileRead.get(i).equals("{")){
      newLine = fileRead.get(i-1);
      newLine += paran;
    }
    else
     output.print(fileRead.get(i)); 
   }



   }

}

最佳答案

I'm suppose to write a program that changes the Java program from next-line brace style to the end-of-line brace style

这是一个你可以做的想法:

  1. 从 Java 文件中逐行读取
  2. 将当前代码行存储到列表中(根据您的要求)
  3. 如果当前行为空(换行符或仅包含空格),emptyLine++;
  4. 继续,直到遇到非空行。
  5. 如果现在您遇到了不以 { 开头的行,添加n列表中的换行数,其中 n equals value of emptyLine然后添加该非空行。 emptyLine = 0;
  6. 否则,如果您点击 { 行,从列表中删除先前添加的字符串中的最后一个换行符,并将当前代码行直接添加到列表中(不添加刚才计算的所有换行符)。 emptyLine = 0;
  7. 继续该过程,直到到达文件末尾。
  8. 关闭文件扫描器并根据您的列表将其写回到文件中。

您可以创建一些辅助方法来帮助您,例如:

public boolean isEmptyLine(String text){
    //Return true if text only contains whitespace, tabs & newline
}

I have no clue where to start and I'm very confused and I don't know how to use Text I/o any thing can help me at this point

我建议您首先进行一些读写文件的练习。

关于java - 改变牙套的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35213817/

相关文章:

java - 在java中创建10个列表的正确且有效的方法?

java - 有没有办法将 ObservableList 绑定(bind)到 ObservableMap?

java - 在Java中读/写数字——转换时出现NumberFormatException

c++ - 将源文件列表放入 Makefile 的最佳方法

java - 仅 Mac 上的异常 : Unexpected end of file from server

java - 使用 Hibernate 和 Criteria 选择最常见的值

java - 为什么按钮不反射(reflect) Action 的 NAME 属性?

Java Arraylist.retainAll() 返回意外的空列表

java - 测试不扩展任何 Spring Data Repository 的存储库

java.io.FileNotFoundException(系统找不到指定的路径)