代碼有點(diǎn)小毛病,不能分開賦值,求大佬指點(diǎn)
父類
package project55;
public abstract class Shape {
? public abstract void c(int a,int b,int r);
? public abstract void s(int a,int b,int r);
}
矩形
package project55;
public class Rectangle extends Shape {
@Override
public void c(int a,int b,int r) {
// TODO Auto-generated method stub
? ? ? ? System.out.println("矩形周長:"+(a+b)*2);
}
@Override
public void s(int a,int b,int r) {
// TODO Auto-generated method stub
? ? ? ? System.out.println("矩形面積:"+a*b);
}
}
圓形
package project55;
public class Circle extends Shape {
? ? double π=3.14;
@Override
public void c(int a,int b,int r) {
// TODO Auto-generated method stub
? ? ? ? System.out.println("圓形的周長:"+π*r*2);
}
@Override
public void s(int a,int b,int r) {
// TODO Auto-generated method stub
? ? ? ? System.out.println("圓形的面積:"+π*r*r);
}
}
Initail函數(shù)
package project55;
import java.util.Scanner;
public class Initail {
public static void main(String[] args) {
// TODO Auto-generated method stub
? ? ? ? Scanner input=new Scanner(System.in);
System.out.print("請輸入矩形的長a:");
int a=input.nextInt();
? ? ? ? System.out.print("請輸入矩形的寬b:");
? ? ? ? int b=input.nextInt();
? ? ? ? System.out.print("請輸入圓形半徑r:");
? ? ? ? int r=input.nextInt();
? ? ? ? Shape shape1=new Rectangle();
? ? ? ? shape1.c(a,b,r);
? ? ? ? shape1.s(a,b,r);
? ? ? ? Shape shape2=new Circle();
? ? ? ? shape2.c(a,b,r);
? ? ? ? shape2.s(a,b,r);
}
}
結(jié)果
請輸入矩形的長a:4
請輸入矩形的寬b:5
請輸入圓形半徑r:6
矩形周長:18
矩形面積:20
圓形的周長:37.68
圓形的面積:113.03999999999999
2018-08-21
你的方法參數(shù)寫錯了。正方形的參數(shù)傳兩個,圓形的傳一個就可以了。main方法中,調(diào)用類方法時(shí),用相應(yīng)的子類去聲明對象,調(diào)用本類的方法。一下是我的代碼,可運(yùn)行
package j2ee;
import java.util.Scanner;
public class HelloWord{
?? ? public static void main(String[] args) {
?? ? Scanner input = new Scanner(System.in);
?? ? System.out.print("請輸入矩形的長a:");
?? ? int a = input.nextInt();
?? ? System.out.print("請輸入矩形的寬b:");
?? ? int b = input.nextInt();
?? ? System.out.print("請輸入圓形的半徑r");
?? ? int r = input.nextInt();
?? ?
?? ? rectangle s1 = new rectangle();
?? ? s1.c(a,b);
?? ? s1.s(a,b);
?? ?
?? ? circle s2 = new circle();
?? ? s2.c(r);
?? ? s2.s(r);
?? ? }
}
?? ??? ?
?? ?
package j2ee;
public abstract class shape {
?public void r(){};
?public void s(){};
}
package j2ee;
import java.util.Scanner;
public class rectangle extends shape {
? public void c(int a,int b){
?? ?? System.out.println(2*(a+b));
? }
? public void s(int a,int b){
?? ?? System.out.println(a*b);
? }
?
}
?? ?? ?
?package j2ee;
public class circle extends shape {
?? ?double π=3.14;
?? ?public void c(int r){
?? ??? ?? System.out.println(2*π*r);
?? ?? }
?? ?? public void s(int r){
?? ?? System.out.println(π*r*r);
?? ?? }
}
2018-08-21
小白的意見,錯了請見諒..
可以先選擇要計(jì)算的圖形形狀,用switch判斷下,然后創(chuàng)建相應(yīng)的實(shí)例...