Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- public class Main {
- private final PushbackReader in;
- private final StringBuilder sb;
- public Main(PushbackReader in) {
- this.in = in;
- sb = new StringBuilder();
- }
- private char read() {
- int read_in = 0;
- try {
- read_in = in.read();
- }
- catch (Exception e) {
- System.exit(1);
- }
- if (read_in == -1) return Character.MIN_VALUE;
- return (char )read_in;
- }
- private void pushBack(char c) {
- try {
- in.unread(c);
- }
- catch (Exception e) {
- System.exit(1);
- }
- }
- public void parse() {
- while (true) {
- char c = read();
- if (c == Character.MIN_VALUE) break;
- if (isLineComment(c)) {
- lineComment();
- continue;
- }
- if (isBlockComment(c)) {
- blockComment();
- continue;
- }
- if (isBreakable(c)) {
- sb.append("\n");
- continue;
- }
- sb.append(c);
- }
- }
- private boolean isBlockComment(char c1) {
- return isComment(c1, '*');
- }
- private boolean isLineComment(char c1) {
- return isComment(c1, '/');
- }
- private boolean isComment(char c1, char comment_char) {
- if (c1 != '/') return false;
- char c2 = read();
- if (c2 != comment_char) {
- pushBack(c2);
- return false;
- }
- sb.append(c1); // c1 is /
- sb.append(c2); // c2 is / or *
- return true;
- }
- private boolean isBreakable(char c) {
- if (Character.isUnicodeIdentifierStart(c) ||
- Character.isUnicodeIdentifierPart(c)) return false;
- return true;
- }
- private void blockComment() {
- char prev = Character.MAX_VALUE;
- do {
- char c1 = read();
- if (c1 == Character.MIN_VALUE) break;
- sb.append(c1);
- if (prev == '*' && c1 == '/') break;
- char c2 = read();
- if (c2 == Character.MIN_VALUE) break;
- sb.append(c2);
- if (c1 == '*' && c2 == '/') break;
- prev = c2;
- } while (true);
- sb.append("\n");
- }
- private void lineComment() {
- while (true) {
- char c = read();
- if (c == Character.MIN_VALUE || c == Character.LINE_SEPARATOR ||
- c == '\r' || c == '\n') break;
- sb.append(c);
- }
- sb.append("\n");
- }
- @Override
- public String toString() {
- return sb.toString();
- }
- public static void main(String[] args) {
- PushbackReader in = null;
- if (args.length > 0) {
- File file = null;
- try {
- file = new File(args[0]);
- }
- catch (Exception e) {
- System.exit(1);
- }
- try {
- in = new PushbackReader(new FileReader(file));
- }
- catch (Exception e) {
- System.exit(1);
- }
- }
- else in = new PushbackReader(new InputStreamReader(System.in));
- Main m = new Main(in);
- m.parse();
- System.out.println(m);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement