课后练习的疑问
父类:
package com.mooc; //抽象类 public abstract class Shape { double a;//长方形边长 double b;//长方形变宽 final double c = 3.14;//圆周率 double d;//圆的半径 public abstract void cal();//抽象方法 }
两个子类:
public class Rectangel extends Shape { public void cal() { System.out.println("长方形的周长为:" + (a+b)*2); System.out.println("长方形的面积为:" + a*b); } }
package com.mooc; public class Circel extends Shape { public void cal() { System.out.println("圆形的周长为:" + 2*c*d); System.out.println("圆形的面积为:" + c*d*d); } }
测试类:
package com.mooc; import java.util.Scanner; public class Inttail { public static void main(String[] args) { // TODO Auto-generated method stub Shape s1 = new Rectangel(); Shape s2 = new Circel(); //获取用户输入的边长和变宽 System.out.println("请输入长方形的边长:"); Scanner input = new Scanner(System.in); s1.a = input.nextDouble(); System.out.println("请输入长方形的边宽:"); Scanner input2 = new Scanner(System.in); s1.b = input2.nextDouble(); //输出长方形的周长和面积 s1.cal(); //获取用户输入的圆的半径 System.out.println("请输入圆形的半径:"); Scanner input3 = new Scanner(System.in); s2.d = input3.nextDouble(); input.close(); input2.close(); input3.close(); //输出圆形的周长和面积 s2.cal(); } }
疑问1:有没有简单的方法关闭输入?
疑问2:如果用下面方法获取输入数据,代码怎么写?
package com.mooc; import java.util.Scanner; public class Int { static Scanner sc = null; Shape s1 = new Rectangel(); Shape s2 = new Circel(); //获取用户输入的长方形边长 public double getA(){ System.out.println("请输入长方形的边长:"); s1.a = sc.nextDouble(); return s1.a; } //获取用户输入的长方形的边宽 public double getB(){ System.out.println("请输入长方形的边宽:"); s1.b = sc.nextDouble(); return s1.b; } //获取用户输入的圆的半径 public double getD(){ System.out.println("请输入圆形的半径:"); s2.d = sc.nextDouble(); return s2.d; } public static void main(String[] args) { //怎么写? } }