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); } }
public void close()关闭此扫描器。
如果此扫描器尚未关闭,并且其底层 readable 也实现 Closeable 接口,则该 readable 的 close 方法将被调用。
System.in是InputStream的对象,并且关掉之后不能再打开
Java 是顺序执行的 你执行到.close() 后就代表 你关闭了 流,你再去调用已经被你关闭的流 显然是不现实的
我的建议是 你做几个方法里面包含输入流,然后在main里面调用就可以了
如果非要用System.in,那么在没有全部读取完之前不要关闭Scanner
使用场景有很多,我在就跟你说一种,适当使用内部类,使得代码更加灵活和富有扩展性。其他场景,随着你深入的学习之后就会接触到法克希特说的对,这里是我不严谨了。感谢指正哈。。