“既走if又走else”的版本间的差异

来自姬鸿昌的知识库
跳到导航 跳到搜索
 
第5行: 第5行:
 
} else {
 
} else {
 
     System.out.println("else");
 
     System.out.println("else");
 +
}
 +
</syntaxhighlight>问题:什么条件可以既走 if 又走 else?
 +
 +
=== 一种思路 ===
 +
<syntaxhighlight lang="java">
 +
public class Test {
 +
 +
/**
 +
* @param args
 +
*/
 +
public static void main(String[] args) {
 +
if (new Object() {
 +
int getStackTraceElementCount() {
 +
int length = Thread.currentThread().getStackTrace().length;
 +
if (length == 3) {
 +
main(args);
 +
}
 +
return length;
 +
}
 +
}.getStackTraceElementCount() > 3) {
 +
System.out.println("if");
 +
} else {
 +
System.out.println("else");
 +
}
 +
}
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>

2024年7月15日 (一) 17:37的最新版本

原题目

if (?){
    System.out.println("if");
} else {
    System.out.println("else");
}

问题:什么条件可以既走 if 又走 else?

一种思路

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if (new Object() {
			int getStackTraceElementCount() {
				int length = Thread.currentThread().getStackTrace().length;
				if (length == 3) {
					main(args);
				}
				return length;
			}
		}.getStackTraceElementCount() > 3) {
			System.out.println("if");
		} else {
			System.out.println("else");
		}
	}
}