标签:can throw article 无法 nbsp string res class 三角形
参考:
开根号 Math.sqrt
mport java.util.*; public class test { public static void main(String[] args){ try { Scanner sc = new Scanner(System.in); System.out.println("请输入加法加法表达式,格式为:21+12+31"); String s = sc.nextLine(); String[] num = s.split("\\+"); int num_1 = Integer.parseInt(num[0]); int num_2 = Integer.parseInt(num[1]); int num_3 = Integer.parseInt(num[2]); int result = num_1+num_2+num_3; System.out.println(num_1 + "+" + num_2 + "+" + num_3 + "=" +result); }catch(Exception e) { System.out.println("Input Error!!"); } } }
public class Triangle { double a; double b; double c; public Triangle( double a, double b, double c ){ this.a = a; this.b = b; this.c = c; } void isTriangle() throws MyException{ if( a+b<=c || a+c<=b || b+c<=a ){ throw new MyException("无法构成三角形,两边之和小于第三边"); } else{ System.out.println("构成三角形"); } } public static void main(String[] args){ Triangle t = new Triangle(2,2,5); try{ t.isTriangle(); }catch(MyException e){ System.out.println(e.getMessage()); }catch(Exception e){ System.out.println("程序发生了其他的异常"); } } } class MyException extends Exception{ String message; public MyException(String ErrorMessage){ message = ErrorMessage; } public String getMessage(){ return message; } }
import java.lang.Math; import java.util.*; abstract class Shape{ abstract protected void getArea(); } class triangle extends Shape{ double a; double b; double c; triangle(double a, double b, double c){ this.a = a; this.b = b; this.c = c; } public void getArea(){ double p = a+b+c/2; System.out.println("三角形面积:" +String.format("%.2f",Math.sqrt(p*(p-a)*(p-b)*(p-c)))); } } class circle extends Shape{ double r; circle(double r){ this.r = r; } public void getArea(){ System.out.println("圆形面积:"+String.format("%.2f",Math.PI*r*r)); } } class rectangle extends Shape{ double x; double y; rectangle( double x, double y ){ this.x = x; this.y = y; } public void getArea(){ System.out.println("矩形面积:"+String.format("%.2f",x*y)); } } class mException extends Exception{ String message; public mException(String ErrorMessage){ message = ErrorMessage; } public String getMessage(){ return message; } } public class Test_3 { triangle t = new triangle(3,4,5); rectangle r = new rectangle(3,4); circle c = new circle(5); void cmd(String s) throws mException{ if( s.equals("1") || s.equals("2") || s.equals("3") ) { switch (s) { case "1": c.getArea(); break; case "2": r.getArea(); break; case "3": t.getArea(); break; } } else{ System.out.println("输入错误"); } } public static void main(String[] args){ Scanner sc = new Scanner(System.in); String s = sc.nextLine(); Test_3 t = new Test_3(); try{ t.cmd(s); }catch(mException e){ System.out.println(e.getMessage()); }catch(Exception e){ System.out.println("程序其他错误"); } } }
标签:can throw article 无法 nbsp string res class 三角形
原文地址:https://www.cnblogs.com/fitzroy343/p/10099729.html