斩月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 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题