我很困惑這兩個決策樹是如何不同的。我正在構建一個應用程序,需要根據從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