有趣的if else
程序员文章站
2022-03-09 18:29:20
...
看下面java代码,调用getString(1)时输出?
class Test {
public String getString(int a) {
String str = "by sea";
if(a>0)
if(a>1) str = "by land";
else str = "";
return str;
}
}
答案是"",不是"by sea"。像c/java之类的语言代码缩进对语义没影响,该else语句匹配最近的if结构。当然上面是段非常不标准的代码,原意是想输出"by sea",所以最好要加{,}
对于python这种强缩进的语言,当然输出"by sea":
#!/usr/bin/python
def getString(a):
str = "by sea"
if a>0:
if a>1: str = "by land"
else: str = ""
return str
print getString(1)