最近中文字幕高清中文字幕无,亚洲欧美高清一区二区三区,一本色道无码道dvd在线观看 ,一个人看的www免费高清中文字幕

為了賬號安全,請及時綁定郵箱和手機立即綁定

以下代碼如何改進?

//父類代碼。
public?abstract?class?shape?{
	public?abstract?void?length();
	public?abstract?void?square();
}
//長方形子類代碼。
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("長方形的周長為:"+length);
	}
	public?void?square()?{
		int??square=w*l;
		System.out.println("長方形的面積為:"+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("圓形的周長為:"+length);
	}
	public?void?square()?{
		double?square=3.14*r*r;
		System.out.println("圓形的面積為:"+square);
	}
}
//測試類代碼。
public?class?test?{
	public?static?void?main(String[]?args)?{
		System.out.println("請輸入您要查詢的圖形類型:1代表長方形,2代表圓形。");
		Scanner?input?=new?Scanner(System.in);
		int?num=input.nextInt();
		switch?(num)?{
		case?1:
			System.out.println("請依次輸入長方形的長度和寬度:");
			shape?shp1=new?rectangle();
			shp1.length();
			shp1.square();			
			break;
		case?2:
			System.out.println("請輸入圓形的半徑:");
			shape?shp2=new?circle();
			shp2.length();
			shp2.square();			
			break;
		default:
			System.out.println("您輸入的數(shù)值有誤,請重新輸入。");
		}
	}
}

我想要的改進是:在用戶輸入其他數(shù)值顯示錯誤后,不用重新運行程序就可以接著接著重新輸入,直到是1或者2

正在回答

2 回答

//測試類代碼。
public?class?test?{
????public?static?void?main(String[]?args)?{
????????
????????//定義一個flag布爾變量
????????boolean?flag?=?true;
????while(flag){
????????System.out.println("請輸入您要查詢的圖形類型:1代表長方形,2代表圓形。");
????????Scanner?input?=new?Scanner(System.in);
????????int?num=input.nextInt();
????????
????????switch?(num)?{
????????case?1:
????????????System.out.println("請依次輸入長方形的長度和寬度:");
????????????shape?shp1=new?rectangle();
????????????shp1.length();
????????????shp1.square();?????????
????????????flag?=?false;
????????????break;
????????case?2:
????????????System.out.println("請輸入圓形的半徑:");
????????????shape?shp2=new?circle();
????????????shp2.length();
????????????shp2.square();?????????
????????????flag?=?false;
????????????break;
????????default:
????????????System.out.println("您輸入的數(shù)值有誤,請重新輸入。");
????????}
????}
????}
}

先定義一個布爾變量,初始值為true,使用while循環(huán)無限循環(huán)。當(dāng)switch條件匹配,則改變flag變量的值為false,
然后break退出switch語句.此時while循環(huán)條件不成立,所以停止循環(huán)。反之,若switch沒有匹配將不會改變flag的值
則不會停止循環(huán).

還有,我提醒一句,你的長方形子類的創(chuàng)建Scanner對象,可以只創(chuàng)建一個。使用同一對象調(diào)用方法。


1 回復(fù) 有任何疑惑可以回復(fù)我~
#1

悅?cè)粺o殤 提問者

確實達(dá)到我想要的效果了,謝謝!
2017-05-21 回復(fù) 有任何疑惑可以回復(fù)我~

編寫一個登錄界面也可以采用這個思路,很棒

0 回復(fù) 有任何疑惑可以回復(fù)我~

舉報

0/150
提交
取消

以下代碼如何改進?

我要回答 關(guān)注問題
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號