请问哪里错了?

来源:10-3 Java 中的抽象类

qq_上帝的智齿_0

2017-04-01 01:25

public class Show {
    public static void main(String[] args) {
		Shape shape1 = new Circle();
		Shape shape2 = new Rectangle();
		shape1.area();
		shape1.grith();
		shape2.area();
		shape2.grith();
	}

}

public abstract class Shape {
	
	public abstract void area();
	public abstract void grith();

}
public class Circle extends Shape {
    double  r ;
	static double pi = 3.14;
	public void area() {
		System.out.print("输入一个半径:");
		Scanner scanner = new Scanner(System.in);
		int r = scanner.nextInt();
		this.r = r;
		scanner.close();
		
		double area = pi*r*r;
		System.out.println("the circle's area is " + area);
	}

	public void grith() {
	    double grith = 2*pi*r;
        System.out.println("the grith is " + grith);
	}

}
public class Rectangle extends Shape{

	static double length = 0;
	static double width = 0;
	public void area() {
		System.out.print("输入长和宽:");
		Scanner scanner = new Scanner(System.in);
		double length = scanner.nextDouble();
		double width = scanner.nextDouble();
		scanner.close();
		
		double area = length*width;
		System.out.println("the rectangle's area is " + area);
	}

	public void grith() {
		// TODO Auto-generated method stub
	
	    double grith = 2*length*width;
        System.out.println("the rectangle's grith is " + grith);
	}

}


写回答 关注

2回答

  • Gir非碼農
    2017-04-01 10:19:18
    已采纳

    public void close()关闭此扫描器。 
    如果此扫描器尚未关闭,并且其底层 readable 也实现 Closeable 接口,则该 readable 的 close 方法将被调用。
    System.in是InputStream的对象,并且关掉之后不能再打开

    Java 是顺序执行的 你执行到.close() 后就代表 你关闭了 流,你再去调用已经被你关闭的流 显然是不现实的
    我的建议是 你做几个方法里面包含输入流,然后在main里面调用就可以了

    如果非要用System.in,那么在没有全部读取完之前不要关闭Scanner


    qq_上帝的...

    非常感谢!

    2017-04-02 15:49:48

    共 1 条回复 >

  • 慕移动9181930
    2022-03-26 18:51:45

    使用场景有很多,我在就跟你说一种,适当使用内部类,使得代码更加灵活和富有扩展性。其他场景,随着你深入的学习之后就会接触到

Java入门第二季 升级版

课程升级!以终为始告别枯燥,在开发和重构中体会Java面向对象编程的奥妙

530105 学习 · 6086 问题

查看课程

相似问题