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

来自姬鸿昌的知识库
跳到导航 跳到搜索
(建立内容为“=== 原题目 ===”的新页面)
 
 
(未显示同一用户的1个中间版本)
第1行: 第1行:
 
=== 原题目 ===
 
=== 原题目 ===
 +
<syntaxhighlight lang="java">
 +
if (?){
 +
    System.out.println("if");
 +
} 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>

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");
		}
	}
}