题目:定义一个形状类Shape,并设置求周长getC方法并实现其方法的重载来求不同形状的周长。 定义一个测试类Test,其main方法中可以求三角形、四边形、五边形的周长。
package shape;//声明包,除默认包不用声明外,别的都必须声明 import java.util.Scanner;//引入Scanner类 public class shape { void getC(float a,float b,float c) {//方法重载,友好方法,可以跨包,但不能跨类 float sum; sum=a+b+c; System.out.println("三角形周长为:"+sum); } void getC(float a,float b,float c,float e){//方法重载 float sum; sum=a+b+c+e; System.out.println("四边形周长为:"+sum); } void getC(float a,float b,float c,float e,float f){//方法重载 float sum; sum=a+b+c+e+f; System.out.println("五边形周长为"+sum); } } //package shape; //import java.util.Scanner; class test { public static void main(String[] args) { // TODO Auto-generated method stub shape ashape=new shape(); System.out.println("请选择要计算的类型:1.三角形 2.四边形 3.五边形 (按序输入)"); Scanner input=new Scanner(System.in); int b=input.nextInt(); switch (b) { case 1: System.out.println("请输入三角形的三边:"); float x=input.nextInt(); float y=input.nextInt(); float z=input.nextInt(); ashape.getC(x,y,z); break; case 2: System.out.println("请输入四边形的四边:"); float a=input.nextInt(); float e=input.nextInt(); float c=input.nextInt(); float d=input.nextInt(); ashape.getC(a,e,c,d); break; case 3: System.out.println("请输入五边形的五边:"); float f=input.nextInt(); float g=input.nextInt(); float h=input.nextInt(); float i=input.nextInt(); float j=input.nextInt(); ashape.getC(f,g,h,i,j); break; default : System.out.println("请重新输入:"); break; } } }重难点 switch(变量){ case 1 : { } case 2 : { } . . . default: break; } 不同的case 项内,定义变量不能重复,不能重名。
