Java Exercise 11.2 Method Overloading

Java Exercise 11.2 Method Overloading


1. Define three overloaded methods to find the average value of two integers, two real numbers, and three integers, respectively, and then call them and output the results, as shown in the figure below

package com.shangjiti.aoian;
import java.util.Scanner;
public class Done1_1 {
    
    
	public static void main(String[] args) {
    
    
		Scanner sc=new Scanner(System.in);
		int num1=sc.nextInt();
		int num2=sc.nextInt();	
		int num3=sc.nextInt();
		double num4=sc.nextDouble();
		double num5=sc.nextDouble();
		System.out.println(avg(num1,num2));
		System.out.println(avg(num1,num2,num3));
		System.out.println(avg(num4,num5));
	}
	public static double avg(int a,int b) {
    
    
		return (a+b)/2.0;			
	}
	public static double avg(int a,int b,int c) {
    
    
		return (a+b+c)/3.0;	
	}
	public static double avg(double d,double e) {
    
    
		return (d+e)/2;		
	}
}

2. First define a method to print the nine-nine-nine multiplication table; then reload the method and add a method to print the nine-nine-nine multiplication table with any number of rows

package com.shangjiti.aoian;
import java.util.Scanner;
public class Done2 {
    
    
	public static void main(String[] args) {
    
    
		Scanner scanner = new Scanner(System.in);
        int x = scanner.nextInt();
        print(x);
    }
    public static void print(){
    
    
        for (int i = 1; i <= 9; i++){
    
    
            for(int j = 1; j <= i; j++)
                System.out.print(j+"*"+i+"="+j*i+"\t");
            System.out.println();
        }
    }
    public static void print(int a){
    
    
        for (int i = 1; i <= a; i++){
    
    
            for(int j = 1; j <= i; j++)
                System.out.print(j+"*"+i+"="+j*i+"\t");
            System.out.println();
        }
	}
}

3. Define two overloaded methods to find the larger value of two integers and the maximum value of three integers respectively

package com.shangjiti.aoian;
public class Done3 {
    
    
	public static void main(String[] args) {
    
    
		System.out.println("两个数最大值是:"+max(65,33));
		System.out.println("三个数最大值是:"+max(26,75,64));
	}
	public static int max(int a,int b){
    
    
		return(a>b)?a:b;
	}
	public static int max(int a,int b,int c){
    
    
		int max =(a>b)?a:b;
		return(max>c)?max:c;
	}
}

Guess you like

Origin blog.csdn.net/m0_46653702/article/details/109379324