當前位置:編程學習大全網 - 源碼下載 - java做壹個計算長方形面積的小程序,怎麽限定小數點只能輸入壹個?怎麽限定只能輸入數字?運算得出的

java做壹個計算長方形面積的小程序,怎麽限定小數點只能輸入壹個?怎麽限定只能輸入數字?運算得出的

import?java.util.Scanner;

import?java.text.DecimalFormat;

public?class?Rectangle?{

public?static?void?main(String[]?args)?{

String?str;

Double?width,?length,?area;

//?判斷小數條件的正則表達式

String?regEx?=?"^([1-9][0-9]*)+(.[0-9]{1,1})?$";?

?

Scanner?s?=?new?Scanner(System.in);

System.out.println("請輸入長:");

str?=?s.nextLine();

while(true)?{

//?若輸入的長度不符合要求,重新輸入。

if?(!str.matches(regEx))?{

System.out.println("輸入格式錯誤,請重新輸入。");

str?=?s.nextLine();

}?else?{

length?=?Double.parseDouble(str);

break;

}

}

System.out.println("請輸入寬:");

str?=?s.nextLine();

while(true)?{

if?(!str.matches(regEx))?{

System.out.println("輸入格式錯誤,請重新輸入。");

str?=?s.nextLine();

}?else?{

width?=?Double.parseDouble(str);

break;

}

}

area?=?width?*?length;

//?定義輸出小數的格式為保留小數點後三位

DecimalFormat?df?=?new?DecimalFormat("###.000");

System.out.println("面積為:"?+?df.format(area));

}

}

運行結果如下

  • 上一篇:跨境出口電商ERP有哪些,哪個好用?
  • 下一篇:為什麽android studio項目不能從u盤復制?
  • copyright 2024編程學習大全網