与胖虎学Java的第四天---类的重载

同时计算int型、double型的加减乘除

 1 package E018;
 2 /*add()、substract()、multiply()
 3 、division()*/
 4 public class Countsum {
 5     public static int add(int a, int b){
 6         return a+b;
 7     }
 8 
 9     public static double add(double x, double y){
10         return x+y;
11     }
12     
13     public static int substract(int a, int b){
14         return a-b;
15     }
16 
17     public static double substract(double x, double y){
18         return x-y;
19     }
20     
21     public static int multiply(int a, int b){
22         return a*b;
23     }
24 
25     public static double multiply(double x, double y){
26         return x*y;
27     }
28     
29     public static int division(int a, int b){
30         if(b==0)
31             return -1;
32         else
33             return a/b;
34     }
35 
36     public static double division(double x, double y){
37         if(y==0)
38             return -1;
39         else
40             return x/y;
41     }
42 
43     public static  String add(String m,String n) {
44         return m+n;
45     }
46     
47 }
 1 package E018;
 2 
 3 import java.util.Scanner;
 4 
 5 
 6 /*.加减乘除功能函数,改造为可以计算两个整数的加减乘除、
 7  * 两个double的加减乘除,以及两个字符串的连接功能(仍旧用add方法)。
 8 
 9 提示:使用函数重载功能,创建不同的add()、substract()、multiply()
10 、division()函数。*/
11 public class Count {
12 
13     
14     public static void main(String[] args) {
15         System.out.println("请输入用于计算的两个数值,数值间用空格间隔:" );
16         Scanner in=new Scanner(System.in);
17         int a=in.nextInt();
18         int b=in.nextInt();
19         double x=in.nextDouble();
20         double y=in.nextDouble();
21         String m=in.next();
22         String n=in.next();
23         in.close();
24  
25         //Countsum countsum1=new Countsum();
26         
27         System.out.println("和为"+Countsum.add(a,b) );
28         System.out.println("和为"+Countsum.add(x,y) );
29         System.out.println("差为"+Countsum.substract(a,b) );
30         System.out.println("差为"+Countsum.substract(x,y) );
31         System.out.println("积为"+Countsum.multiply(a,b) );
32         System.out.println("积为"+Countsum.multiply(x,y) );
33         
34         int e=Countsum.division(a,b);
35         if(b==0){
36             System.out.println("分母不能为0");
37         }
38         else{
39             System.out.println("商为:"+e);
40         }
41         
42         double f=Countsum.division(x,y);
43         if(y==0){
44             System.out.println("分母不能为0");
45         }
46         else{
47             System.out.println("商为:"+f);
48         }
49         
50         String i=Countsum.add(m,n);
51         {
52             System.out.println("连接字符串为:"+i); 
53         }       
54         
55     }
56 
57     
58 
59 
60 }

原文地址:https://www.cnblogs.com/dede-6/p/11752815.html