public?class?Show?{
????public?static?void?main(String[]?args)?{
Shape?shape1?=?new?Circle();
Shape?shape2?=?new?Rectangle();
shape1.area();
shape1.grith();
shape2.area();
shape2.grith();
}
}
public?abstract?class?Shape?{
public?abstract?void?area();
public?abstract?void?grith();
}
public?class?Circle?extends?Shape?{
????double??r?;
static?double?pi?=?3.14;
public?void?area()?{
System.out.print("輸入一個半徑:");
Scanner?scanner?=?new?Scanner(System.in);
int?r?=?scanner.nextInt();
this.r?=?r;
scanner.close();
double?area?=?pi*r*r;
System.out.println("the?circle's?area?is?"?+?area);
}
public?void?grith()?{
????double?grith?=?2*pi*r;
????????System.out.println("the?grith?is?"?+?grith);
}
}
public?class?Rectangle?extends?Shape{
static?double?length?=?0;
static?double?width?=?0;
public?void?area()?{
System.out.print("輸入長和寬:");
Scanner?scanner?=?new?Scanner(System.in);
double?length?=?scanner.nextDouble();
double?width?=?scanner.nextDouble();
scanner.close();
double?area?=?length*width;
System.out.println("the?rectangle's?area?is?"?+?area);
}
public?void?grith()?{
//?TODO?Auto-generated?method?stub
????double?grith?=?2*length*width;
????????System.out.println("the?rectangle's?grith?is?"?+?grith);
}
}
2017-04-01
public?void?close()關閉此掃描器。?
如果此掃描器尚未關閉,并且其底層?readable?也實現?Closeable?接口,則該?readable?的?close?方法將被調用。
System.in是InputStream的對象,并且關掉之后不能再打開
Java?是順序執行的?你執行到.close()?后就代表?你關閉了?流,你再去調用已經被你關閉的流?顯然是不現實的
我的建議是?你做幾個方法里面包含輸入流,然后在main里面調用就可以了
如果非要用System.in,那么在沒有全部讀取完之前不要關閉Scanner
2022-03-26
使用場景有很多,我在就跟你說一種,適當使用內部類,使得代碼更加靈活和富有擴展性。其他場景,隨著你深入的學習之后就會接觸到法克希特說的對,這里是我不嚴謹了。感謝指正哈。。