Java:Counter Indentation

时间:2015-11-25 20:57:16

标签: java

我是java的新手,并试图创建一个java应用程序(当在终端内运行时)将复制内部的文本,如果有一个卷曲{括号然后添加3个空格,当有一个卷曲}括号然后删除3个空格。每次出现{em>(参见示例)

时,应该有一个计数器来缩进另外3个空格

示例: File1.txt

Hello{StackOverflow}{Users}

输出应为 File2.txt

Hello
{
   StackOverflow
}

{
      Users
}

我目前输入的 File2.txt 是:

Hello
{
   StackOverflow
}

{
   Users

我错过了我的最后一个括号(我该如何解决?)并且不知道如何基于计数器循环缩进。请帮忙

我目前的代码:

import java.io;
import java.util.Scanner;

public class myapp {

    public static void main(String[] argv) throws IOException {

        File InputFile = new File(argv[0]);
        Scanner FileScanner = new Scanner(InputFile);
        FileWriter Writer = new FileWriter(argv[1]);
        BufferedWriter OutputWriter = new BufferedWriter(Writer);

        while (FileScanner.hasNextLine() == true) {
            String a = FileScanner.nextLine();

            try {
                int indent = 0;
                {

                    if (a.contains("{")) {
                        indent++;

                    }

                    for (int i = 0; i < indent; i++) {

                        OutputWriter.write("   ");
                    }
                    OutputWriter.write(a);
                }

                if (a.contains("}")) {
                    indent--;

                }

            } catch (Exception e) {
                System.out.println("Error:" + e.getMessage());
            }
            OutputWriter.write("}");
        }
    }
}
终端中的

p.s(运行/测试)我使用以下命令:

$java myapp File1.txt File2.txt

谢谢:)

3 个答案:

答案 0 :(得分:0)

尝试通过OutputWriter.close()关闭方法末尾的}。它会刷新流,这可能是导致丢失indent的原因。

就缩进问题而言,在循环外声明并初始化 <form enctype="multipart/form-data"> <input id="fileupload" type="file" name="files[]" class="files " onChange="UploadImage" accept='image/*'/> <input type="button" class="submit_form" value="submit"> </form> <?php add_action( 'wp_ajax_UploadImage', 'UploadImage' ); function UploadImage() { $upload_dir = wp_upload_dir(); $files = $_FILES['files']; //Some function } ?> 计数器。否则,每次迭代都会重置为0。

答案 1 :(得分:0)

试试这个,我可以添加 finally{ OutputWriter.close(); } 块。

from .fel import fel

fel(something)

答案 2 :(得分:0)

试试这个:

public static void main(String[] args) throws IOException {
 File InputFile = new File(argv[0]);
 Scanner FileScanner = new Scanner(InputFile);
 FileWriter Writer = new FileWriter(argv[1]);
 BufferedWriter OutputWriter = new BufferedWriter(Writer);
 while (FileScanner.hasNextLine() == true) {
  String a = FileScanner.nextLine();
  String b = "";
  for (int i = 0; i < a.length(); i++) {
   if (a.charAt(i) == '{') {
     b += "\n{\n   ";
   } else if (a.charAt(i) == '}') {
     b += "\n}\n";
   } else {
     b += a.charAt(i);
   }
}
OutputWriter.write(b);
OutputWriter.close();
}}}