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("輸入一個(gè)半徑:");
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("輸入長(zhǎng)和寬:");
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()關(guān)閉此掃描器。?
如果此掃描器尚未關(guān)閉,并且其底層?readable?也實(shí)現(xiàn)?Closeable?接口,則該?readable?的?close?方法將被調(diào)用。
System.in是InputStream的對(duì)象,并且關(guān)掉之后不能再打開
Java?是順序執(zhí)行的?你執(zhí)行到.close()?后就代表?你關(guān)閉了?流,你再去調(diào)用已經(jīng)被你關(guān)閉的流?顯然是不現(xiàn)實(shí)的
我的建議是?你做幾個(gè)方法里面包含輸入流,然后在main里面調(diào)用就可以了
如果非要用System.in,那么在沒有全部讀取完之前不要關(guān)閉Scanner
2022-03-26
使用場(chǎng)景有很多,我在就跟你說一種,適當(dāng)使用內(nèi)部類,使得代碼更加靈活和富有擴(kuò)展性。其他場(chǎng)景,隨著你深入的學(xué)習(xí)之后就會(huì)接觸到法克希特說的對(duì),這里是我不嚴(yán)謹(jǐn)了。感謝指正哈。。