Büni
Büni

Reputation: 33

How can a program print its own source code without reading any file

I've to write a code that outputs its own source code, but I am not allowed to read it from the file.

This is what we got from the teacher:

public class SelfPrint {
  public static void main(String[] args) {
      System.out.print(getMyText());
  }
  private static String programText [] = {
      ....
  };
  private static String getMyText() {
  }
  
}

Upvotes: 0

Views: 221

Answers (1)

user17233545
user17233545

Reputation:

Try this.

getMyText has three for statements. The first one prints the first 5 lines of the program. The second one prints the constant value of programText. And the last one prints the rest of the program. So programText will be printed twice.

public class SelfPrint {
    public static void main(String[] args) {
        System.out.print(getMyText());
    }
    private static String[] programText = {
"public class SelfPrint {",
"    public static void main(String[] args) {",
"        System.out.print(getMyText());",
"    }",
"    private static String[] programText = {",
"    };",
"    private static String getMyText() {",
"        char q = 34, c = 44;",
"        String n = System.lineSeparator();",
"        StringBuilder sb = new StringBuilder();",
"        for (int i = 0; i < 5; i++)",
"            sb.append(programText[i]).append(n);",
"        for (int i = 0; i < programText.length; i++)",
"            sb.append(q + programText[i] + q + c).append(n);",
"        for (int i = 5; i < programText.length; i++)",
"            sb.append(programText[i]).append(n);",
"        return sb.toString();",
"    }",
"}",
    };
    private static String getMyText() {
        char q = 34, c = 44;
        String n = System.lineSeparator();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 5; i++)
            sb.append(programText[i]).append(n);
        for (int i = 0; i < programText.length; i++)
            sb.append(q + programText[i] + q + c).append(n);
        for (int i = 5; i < programText.length; i++)
            sb.append(programText[i]).append(n);
        return sb.toString();
    }
}

Test (on Windows11)

C:\temp>javac SelfPrint.java

C:\temp>java SelfPrint > out

C:\temp>diff SelfPrint.java out

C:\temp>echo %ERRORLEVEL%
0

Upvotes: 1

Related Questions