我很困惑这两个决策树是如何不同的。我正在构建一个应用程序,需要根据从ListView中选择的位置来决定加载哪个视图。我试图将逻辑构建到单个控制器模块中,并发现switch-case将导致NullPointerException和FC,而if-else将完美工作。任何人都可以启发我为什么?我在C和C++中拥有强大的背景,并且习惯于能够轻松地将开关重新写入if-else,反之亦然。Android/Java问题。这两种决策树如何不同?
定义瓦尔:
private final int VALUEA = 0;
private final int VALUEB = 1;
private final int VALUEC = 2;
开关情况下:
TextView t = new TextView(null);
switch(value){
case VALUEA:
setContentView(R.layout.valuealayout);
t = (TextView) findViewById(R.id.valuealayout);
t.findViewById(R.id.valuealayout);
break;
case VALUEB:
setContentView(R.layout.valueblayout);
t = (TextView) findViewById(R.id.valueblayout);
t.findViewById(R.id.valueblayout);
break;
case VALUEC:
setContentView(R.layout.valueclayout);
t = (TextView) findViewById(R.id.valueclayout);
t.findViewById(R.id.valueclayout);
break;
default:
break;
}
的块上方将导致一个NullPointerException。
的if-else:
if(value == VALUEA){
setContentView(R.layout.valuealayout);
TextView t = (TextView) findViewById(R.id.valuealayout);
t.findViewById(R.id.valuealayout);
}else if(value == VALUEB){
setContentView(R.layout.valueblayout);
TextView t = (TextView) findViewById(R.id.valueblayout);
t.findViewById(R.id.valueblayout);
}else if(value == VALUEC){
setContentView(R.layout.valueclayout);
TextView t = (TextView) findViewById(R.id.valueclayout);
t.findViewById(R.id.valueclayout);
}else{
}
该版本完美的作品。第二个块是否因为一些时髦的Java范围规则而工作,该规则允许决策树的每个分支以第一个块没有的方式创建和正确初始化TextView?
哪条线会抛出NPE? – 2011-06-15 05:40:54