在Java中三種計算不同形狀面積(三角形、正方形、長方形)的實現
技術標籤:java
//根據使用者不同的選擇計算不同形狀的面積(三角形、正方形、長方形)用不同方式實現:
// 1.引數和麵積在自定義方法中輸入和輸出
public class Hello1 {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println(“請輸入您要輸入的形狀:三角形–1,正方形–2,長方形–3”);
int form = sc.nextInt();
//呼叫方法 calArea(form); } public static void calArea(int form){ switch(form){ case 1: System.out.println("請輸入三角形的底邊:"); double bottom = sc.nextDouble(); System.out.println("請輸入三角形的高"); double height = sc.nextDouble(); System.out.println("三角形的面積為:"+bottom*height/2); break; case 2: System.out.println("請輸入正方形邊:"); double side = sc.nextDouble(); System.out.println("正方形的面積為:"+side*side); break; case 3: System.out.println("請輸入長方形的邊:"); double bottom1 = sc.nextDouble(); System.out.println("請輸入長方形的高"); double width = sc.nextDouble(); System.out.println("長方形的面積為:"+bottom1*width); break; } }
}
// 2.引數在主方法中接收
public class Hello2 {
static Scanner sc = new Scanner(System.in);
public static void main(String[] ages){
System.out.println(“請輸入您要輸入的形狀:三角形–1,正方形–2,長方形–3”);
int form = sc.nextInt();
switch(form){
case 1:
System.out.println(“請輸入三角形的底邊:”);
double bottom = sc.nextDouble();
System.out.println(“請輸入三角形的高”);
break;
case 2:
System.out.println(“請輸入正方形邊:”);
double side = sc.nextDouble();
break; case 3: System.out.println("請輸入長方形的高:"); double height1 = sc.nextDouble(); System.out.println("請輸入長方形的寬"); double width = sc.nextDouble(); break; } } public static void calTriangle(double bottom,double height){ System.out.println("三角形的面積為:"+bottom*height/2); } public static void calSquare(double side){ System.out.println("正方形的面積為:"+side*side); } public static void calRectangle(double width,double height1){ System.out.println("長方形的面積為:"+height1*width); }
}
//3.引數在主方法中接收並且在主方法中要計算面積和
public class Hello3 {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println(“請輸入您要計算的圖形:(三角形–1、正方形–2、長方形–3)”);
int i = sc.nextInt();
//呼叫方法
calArea(i);
}
public static void calArea(int i){
switch(i){
case 1:
System.out.println("請輸入三角形的底邊");
double bottom = sc.nextInt();
System.out.println("請輸入三角形的高");
double height = sc.nextInt();
System.out.println("三角形的面積為:"+bottom*height/2);
break;
case 2:
System.out.println("請輸入正方形的邊");
double side = sc.nextInt();
System.out.println("三角形的面積為:"+side);
break;
case 3:
System.out.println("請輸入長方形的寬");
double width = sc.nextInt();
System.out.println("請輸入長方形的高");
double height1 = sc.nextInt();
System.out.println("三角形的面積為:"+width*height1);
break;
}
}
}