斩月sama 2015-04-16 09:34 采纳率: 66.7%
浏览 2828
已采纳

求帮忙理解一个JAVA程序,该程序的功能是将次行块风格的代码转换成行尾块

package exercise_9;
import java.util.*;
import java.io.*;

public class Exercise9_16 {
/**Main method*/
public static void main(String[] args) throws Exception {
// Check command line parameter usage
if (args.length != 1) {
System.out.println(
"Usage: java Exercise9_16 filename");
System.exit(0);
}

// Check if source file exists
File sourceFile = new File(args[0]);
if (!sourceFile.exists()) {
   System.out.println("Source file " + args[0] + " not exist");
   System.exit(0);
}

StringBuilder buffer = new StringBuilder();
Scanner input = new Scanner(sourceFile);

while (input.hasNext()) {
  String s = input.nextLine();//一行行输入
  String s1 = s.trim();//把多出来的空格都删掉
  if (s1.charAt(0) == '{') {
    buffer.append(" {");
    if (s1.length() > 1) buffer.append("\r\n" + s.replace('{', ' '));
  }
  else
    buffer.append("\r\n" + s);
}

input.close();

// Write buffer into the file
PrintWriter output = new PrintWriter(sourceFile);
output.print(buffer.toString());
output.close();

}
}


if (s1.charAt(0) == '{') {这一行开始就看不太懂了,求解答

  • 写回答

1条回答 默认 最新

  • danielinbiti 2015-04-16 09:53
    关注

    比如

     public void a()
    {if(true)
    {}
    }
    第一次读入 public void a(),放入了buffer中
    读取到{if(true)时,判断到开始是{,那么把{放入buffer中,因为没有回车换行,也就是拼接到了public void a()后面,成了public void a() {
    然后把buffer再拼接"\r\n"换行,s.replace('{', ' ')替换到第一个{,剩下if(true)放入buffer中,这就出来结果
    public void a() {
      if(true)
    这种效果了。
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改