在一次采访中,我被问到如何在执行同一程序时将整个源程序显示为输出。
File-handling概念来完成这个任务,还有其他方法来完成这个任务吗?有什么建议吗?
更新解决方案: --当我研究一些我得到的解决方案时,我们可以通过奎因来完成
String array..as @Basile,如下所示发布于 2013-10-26 05:44:23
这是一个程序,当运行时将显示itself.The秘密是创建一个包含程序行的字符串数组,除了数组itself.So中的String之外,您有第一个循环来显示Strings.Then数组之前的代码行,您有一个循环来显示数组字符串,然后有一个循环来显示代表剩余代码行的数组字符串。
请注意,空格字符的ASCII值为32,双引号的ASCII值为34。下面创建“引号”和“sixSpaces”的原因是,在显示它们时,必须避免使用转义字符\,然后在显示引号时使用转义字符。
public class ProgramThatDisplaysItself {
public static void main(String[] args) {
char space = (char)32;
char quote = (char)34;
String emptyStr = new String();
String spaceStr = String.valueOf(space);
String sixSpaces =
emptyStr.concat(spaceStr).concat(spaceStr).concat(spaceStr)
.concat(spaceStr).concat(spaceStr).concat(spaceStr);
String linesOfCode[] = {
"package programthatdisplaysitself;",
"",
"public class ProgramThatDisplaysItself {",
"",
" public static void main(String[] args) {",
" char space = (char)32;",
" char quote = (char)34;",
" String emptyStr = new String();",
" String spaceStr = String.valueOf(space);",
" String sixSpaces = ",
" emptyStr.concat(spaceStr).concat(spaceStr).concat(spaceStr)",
" .concat(spaceStr).concat(spaceStr).concat(spaceStr);",
"",
" String linesOfCode[] = {",
// Note: here's where the String array itself is skipped
" };",
"",
" for ( int i = 0; i < 14; i++ ) {",
" System.out.println( linesOfCode[i] );",
" } // end for i",
"",
" for ( int j = 0; j < linesOfCode.length; j++ ) {",
" System.out.println( sixSpaces + quote + linesOfCode[j] + quote + ',' );",
" } // end for j",
"",
" for ( int k = 14; k < linesOfCode.length; k++ ) {",
" System.out.println( linesOfCode[k] );",
" } // end for k",
"",
" } // end main()",
"",
"} // end class ProgramThatDisplaysItself",
}; // end linesOfCode[]
//display the lines until the String array elements
for ( int i = 0; i < 14; i++ ) {
System.out.println( linesOfCode[i] );
} // end for i
//display the String array elements
for ( int j = 0; j < linesOfCode.length; j++ ) {
System.out.println( sixSpaces + quote + linesOfCode[j] + quote + ',' );
} // end for j
//display the lines after the String array elements
for ( int k = 14; k < linesOfCode.length; k++ ) {
System.out.println( linesOfCode[k] );
} // end for k
} // end main()
} // end class ProgramThatDisplaysItself发布于 2013-10-26 05:21:27
一旦它在字节码中,我不认为你能从它得到源代码。实现这一点的唯一方法是,如果程序保存了它的代码的字符串副本,或者从用于编译和打印它的文件中加载相同的源文件。
编辑:在检查Quine计算机之后,示例是在程序中使用字符串,并使用代码的副本。
发布于 2013-10-26 05:27:11
您可以像这样编写代码来打印源代码。这就是你要找的东西吗?
class A{
public static void main(String args[]) throws Exception {
FileReader f = new FileReader(filePathOfThisClass);
BufferedReader b = new BufferedReader(f);
String s= null;
while ((str = b.readLine()) != null)
System.out.println(s);
}
}更新
根据Basile的评论,我很好奇。因此我找到了几种选择。检查此页面,例如从quine页面中的程序。
java.txt
https://stackoverflow.com/questions/19603099
复制相似问题