標籤:... java 字串 限制 技術 代碼 port nbsp imp
今天看到一個很有意思的問題,如何輸出一個程式自己的源碼,看到這個問題的第一反應自然是讀取源碼檔案,然後逐行輸出即可。
但是,如果加上限制條件不能讀取檔案呢?
emmm...思考許久之後,WIKI解救了我,以下內容皆摘自wiki。先上源碼。
public class Quine{ public static void main(String[] args) { char q = 34; // Quotation mark character String[] l = { // Array of source code "public class Quine", "{", " public static void main(String[] args)", " {", " char q = 34; // Quotation mark character", " String[] l = { // Array of source code", " ", " };", " for(int i = 0; i < 6; i++) // Print opening code", " System.out.println(l[i]);", " for(int i = 0; i < l.length; i++) // Print string array", " System.out.println(l[6] + q + l[i] + q + ‘,‘);", " for(int i = 7; i < l.length; i++) // Print this code", " System.out.println(l[i]);", " }", "}", }; for(int i = 0; i < 6; i++) // Print opening code System.out.println(l[i]); for(int i = 0; i < l.length; i++) // Print string array System.out.println(l[6] + q + l[i] + q + ‘,‘); for(int i = 7; i < l.length; i++) // Print this code System.out.println(l[i]); }}
程式前半部分是java運行必須的首碼,再添加一個變數q(內容為引號“”),中間部分一個字串數組記錄整個程式源碼(包含輸出的源碼),後半部分是用來輸出的源碼。emm反正看完這個代碼,感覺豁然開朗,本篇部落格也不算是一篇技術部落格,只是對Quine做一個記錄,如果看到本篇部落格對其他語言如何?Quine好奇的可以查看 https://en.m.wikipedia.org/wiki/Quine_(computing) ,源碼也是wiki上的。
下面的源碼是在Quine的基礎上,略微修改了一點點把java源碼中package包也輸出的實現。(其實沒改什麼,主要還是Quine的實現厲害2333)。
package xjbg;public class Quine{ public static void main(String[] args) { char q = 34; // Quotation mark character String[] l = { // Array of source code "package xjbg;", "", "public class Quine", "{", " public static void main(String[] args)", " {", " char q = 34; // Quotation mark character", " String[] l = { // Array of source code", " ", " };", " for(int i = 0; i < 8; i++) // Print opening code", " System.out.println(l[i]);", " for(int i = 0; i < l.length; i++) // Print string array", " System.out.println(l[8] + q + l[i] + q + ‘,‘);", " for(int i = 9; i < l.length; i++) // Print this code", " System.out.println(l[i]);", " }", "}", }; for(int i = 0; i < 8; i++) // Print opening code System.out.println(l[i]); for(int i = 0; i < l.length; i++) // Print string array System.out.println(l[8] + q + l[i] + q + ‘,‘); for(int i = 9; i < l.length; i++) // Print this code System.out.println(l[i]); }}
如果有import也可以加到數組開頭,那麼本篇記錄部落格到此結束啦!
Quine--輸出程式源碼的程式(java)