以下代碼如何改進(jìn)?
//父類代碼。
public?abstract?class?shape?{
public?abstract?void?length();
public?abstract?void?square();
}
//長(zhǎng)方形子類代碼。
public?class?rectangle?extends?shape?{
Scanner?scan1=new??Scanner(System.in);
int?l=scan1.nextInt();
Scanner?scan2=new??Scanner(System.in);
int?w=scan2.nextInt();
public?void?length()?{
int??length=2*(l+w);
System.out.println("長(zhǎng)方形的周長(zhǎng)為:"+length);
}
public?void?square()?{
int??square=w*l;
System.out.println("長(zhǎng)方形的面積為:"+square);
}
}
//圓形子類代碼。
public?class?circle?extends?shape?{
Scanner?scan1=new??Scanner(System.in);
double?r=scan1.nextDouble();
public?void?length()?{
double?length=2*3.14*r;
System.out.println("圓形的周長(zhǎng)為:"+length);
}
public?void?square()?{
double?square=3.14*r*r;
System.out.println("圓形的面積為:"+square);
}
}
//測(cè)試類代碼。
public?class?test?{
public?static?void?main(String[]?args)?{
System.out.println("請(qǐng)輸入您要查詢的圖形類型:1代表長(zhǎng)方形,2代表圓形。");
Scanner?input?=new?Scanner(System.in);
int?num=input.nextInt();
switch?(num)?{
case?1:
System.out.println("請(qǐng)依次輸入長(zhǎng)方形的長(zhǎng)度和寬度:");
shape?shp1=new?rectangle();
shp1.length();
shp1.square();
break;
case?2:
System.out.println("請(qǐng)輸入圓形的半徑:");
shape?shp2=new?circle();
shp2.length();
shp2.square();
break;
default:
System.out.println("您輸入的數(shù)值有誤,請(qǐng)重新輸入。");
}
}
}我想要的改進(jìn)是:在用戶輸入其他數(shù)值顯示錯(cuò)誤后,不用重新運(yùn)行程序就可以接著接著重新輸入,直到是1或者2
2017-05-20
//測(cè)試類代碼。 public?class?test?{ ????public?static?void?main(String[]?args)?{ ???????? ????????//定義一個(gè)flag布爾變量 ????????boolean?flag?=?true; ????while(flag){ ????????System.out.println("請(qǐng)輸入您要查詢的圖形類型:1代表長(zhǎng)方形,2代表圓形。"); ????????Scanner?input?=new?Scanner(System.in); ????????int?num=input.nextInt(); ???????? ????????switch?(num)?{ ????????case?1: ????????????System.out.println("請(qǐng)依次輸入長(zhǎng)方形的長(zhǎng)度和寬度:"); ????????????shape?shp1=new?rectangle(); ????????????shp1.length(); ????????????shp1.square();????????? ????????????flag?=?false; ????????????break; ????????case?2: ????????????System.out.println("請(qǐng)輸入圓形的半徑:"); ????????????shape?shp2=new?circle(); ????????????shp2.length(); ????????????shp2.square();????????? ????????????flag?=?false; ????????????break; ????????default: ????????????System.out.println("您輸入的數(shù)值有誤,請(qǐng)重新輸入。"); ????????} ????} ????} } 先定義一個(gè)布爾變量,初始值為true,使用while循環(huán)無(wú)限循環(huán)。當(dāng)switch條件匹配,則改變flag變量的值為false, 然后break退出switch語(yǔ)句.此時(shí)while循環(huán)條件不成立,所以停止循環(huán)。反之,若switch沒(méi)有匹配將不會(huì)改變flag的值 則不會(huì)停止循環(huán). 還有,我提醒一句,你的長(zhǎng)方形子類的創(chuàng)建Scanner對(duì)象,可以只創(chuàng)建一個(gè)。使用同一對(duì)象調(diào)用方法。2017-06-04
編寫一個(gè)登錄界面也可以采用這個(gè)思路,很棒