-
编写一个Java应用程序﹐定义一个父类,该父类有一个方法,方法有两个字符串参数,该方法将实现两字符串的拼接,定义两个子类重写上述父类的方法,分别实现整数相加(需要将字符串转为整数),浮点数相加(需要将字符串转为整数)。要进行异常处理,对输入的不符合要求的字符串提示给用户,不能使程序崩溃。
-
代码如下
-
菜鸡一枚,不喜勿喷
package com.itxiaotiancai.Example8_2; import java.util.Scanner; class father { void link() { String A; String B; String C; Scanner sc = new Scanner(System.in); A=sc.nextLine(); B=sc.nextLine(); C =A + B; System.out.println(C); } } class son extends father { void link(){ Scanner sc = new Scanner(System.in); String D; String E; int F; int C; D=sc.nextLine(); String regex="^-?\\d+(\\.\\d+)?$"; if(D.matches(regex)){ System.out.println("输入正确"); } else{ System.out.println("输入错误,请从新输入"); } E=sc.nextLine(); if(E.matches(regex)){ System.out.println("输入正确"); } else{ System.out.println("输入错误,请从新输入"); } C=Integer.parseInt(D); F=Integer.parseInt(E); System.out.println(C+F); } } class son2 extends father{ void link(){ Scanner sc = new Scanner(System.in); String G; String H; String regex="\\d+\\.\\d+"; G=sc.nextLine(); if(G.matches(regex)){ System.out.println("输入正确"); } else{ System.out.println("输入错误,请从新输入"); } H=sc.nextLine(); if(H.matches(regex)){ System.out.println("输入正确"); } else{ System.out.println("输入错误,请从新输入"); } double X=Double.parseDouble(G); double Y=Double.parseDouble(H); System.out.println(X+Y); } } public class Example8_2 { public static void main(String[] args) { father A=new father(); A.link(); son B=new son(); B.link(); son2 C=new son2(); C.link(); } }
编写一个Java应用程序﹐定义一个父类,该父类有一个方法,方法有两个字符串参数,该方法将实现两字符串的拼接,定义两个子类重写上述父类的方法分别实现整数相加(需要将字符串转为整数),浮点数相加
最新推荐文章于 2023-04-17 15:59:39 发布