java - 在Java中的抽象类中获取运行时输入
问题描述
问题陈述是“开发一个 Java 程序来创建一个名为的抽象类
Shape
,其中包含两个整数和一个名为的空方法printArea()
。提供三个名为 的类Rectangle
,Triangle
并且Circle
每个类都扩展类 Shape。每个类仅包含printArea()
打印给定形状区域的方法。”
在这个程序中,我想Shape
从用户(运行时)而不是编译时获取抽象类包含的两个整数值。
这是我的代码
abstract class Shape
{
abstract void Printarea();
int a=10,b=2;;
}
class Rectangle extends Shape
{
void Printarea()
{
System.out.println("area of rectangle is "+(a*b));
}
}
class Triangle extends Shape
{
void Printarea()
{
System.out.println("area of triangle is "+(0.5*a*b));
}
}
class Circle extends Shape
{
void Printarea()
{
System.out.println("area of circle is "+(3.14*a*a));
}
}
class Main
{
public static void main(String []args)
{
Shape=b;
b=new Circle();
b.Printarea();
b=new Rectangle();
b.Printarea();
b=new Triangle();
b.Printarea();
}
}
解决方案
一些快速的代码,但按预期工作,会给你的想法:
import java.util.Scanner;
abstract class Shape {
int a = 10, b = 2;
Shape(int a, int b){
this.a=a;
this.b=b;
}
abstract void Printarea();
}
class Rectangle extends Shape {
Rectangle(int a, int b) {
super(a, b);
}
void Printarea() {
System.out.println("area of rectangle is " + (a * b));
}
}
class Triangle extends Shape {
Triangle(int a, int b) {
super(a, b);
}
void Printarea(){
System.out.println("area of triangle is " + (0.5 * a * b));
}
}
class Circle extends Shape {
Circle(int a, int b) {
super(a, b);
}
void Printarea() {
System.out.println("area of circle is " + (3.14 * a * a));
}
}
class Z {
public static void main(String[] args){
Shape shape=null;
String input;
int width, height;
while (true) {
Scanner scanner = new Scanner(System.in);
System.out.println("which shape? circle/rectangle/triangle (write any other thing for quitting): ");
input = scanner.nextLine();
if(!"circle".equalsIgnoreCase(input) && !"rectangle".equalsIgnoreCase(input) && !"triangle".equalsIgnoreCase(input) ){
System.exit(0);
}
System.out.println("height: ");
height = scanner.nextInt();
System.out.println("width: ");
width = scanner.nextInt();
if("circle".equalsIgnoreCase(input)){
shape=new Circle(width, height);
}
else if("rectangle".equalsIgnoreCase(input)){
shape=new Rectangle(width, height);
}
else{ // == triangle
shape=new Triangle(width, height);
}
shape.Printarea();
}
}
}
推荐阅读
- oracle - SQL 函数和案例返回问题
- python - Python PATH 问题窗口
- c# - 如何使用 C# wpf (writablebitmap) 录制流视频
- javascript - 如何使用 socket.io-client 更新 useEffect 挂钩中的 React 状态
- reactjs - Gatsby Starter 博客图片未加载
- scala - 斯卡拉。追加到 Map 的值,即 ListBuffer
- node.js - “没有'new'就不能调用类构造函数联盟” TypeORM QueryBuilder 错误
- java - 在Android中以编程方式拨打多个号码?
- python - 我需要将数据类型为对象的日期列转换为日期时间
- flutter - “字符串”不是“列表”类型的子类型