一. 没有具体返回值类型的方法
没有具体返回值的方法的定义(Java语法规定:需要使用 void 代替 返回值类型)
遵循定义方法的格式
public static void 方法名(形式参数列表){
…
}
调用这种类型方法:
单独调用
需求:
键盘录入一个数据n(1-9):打印nn乘法表
打印z行m列的*形
*/
//导包
import java.util.Scanner ;
class FunctionDemo{
public static void main(String[] args){
//创建键盘录入对象
Scanner sc = new Scanner(System.in) ;
//提示并录入数据
System.out.println("请输入一个数据N(1-9):") ;
int n = sc.nextInt() ;
//调用方法:打印nn乘法表
printNN(n) ;
System.out.println("--------------------------------") ;
//打印z行m列的*形
System.out.println("请输入行数z:") ;
int z = sc.nextInt() ;
System.out.println("请输入列数m:") ;
int m = sc.nextInt() ;
//调用方法
printStar(z,m) ;
}
/*
定义方法:
两个明确
1)明确返回值类型:void代替
2)明确参数类型以及参数个数: int 两个参数
*/
public static void printStar(int z,int m){
for(int x = 0 ; x <= z ; x ++){
for(int y = 0 ; y <= m ; y ++){
System.out.print("*");
}
System.out.println();
}
}
/*
定义方法:
两个明确
1)明确返回值类型: 用void 代替
2)明确参数类型以及参数个数:int 1个参数
*/
public static void printNN(int n){
//外层循环控制行数
for(int x = 1 ; x <= n ; x ++){
//内层循环列数在变化: <=x
for(int y =1 ; y <=x ; y ++){
System.out.print(x+"*"+y+"="+(y*x)+"\t") ;
}
System.out.println() ;
}
}
二.方法重载
需求:
求数据之和!(默认 int类型)
上面这个需求:没有明确求几个数据,按照以下代码
两个数据,三个数据,四个数据分别求和!
按照 "标识符"的规则:定义方法: 见名知意
Java规定:如果很多个功能都是一样的,又做到方法名要见名知意:
方法重载(OverLoad):方法名相同,参数列表不同,与返回值无关!
参数列表不同:
1)参数个数不一样
2)参数类型不一样
public static int compare(int a,int b){}
public static float compare(float a,float b){}
public static int compare(float a,int b){}
public static int compare(float a,double b){}
Java中的方法重载:为了提供这个功能扩展性:方法名相同,可以接收各种类型的参数!
举例:
Math类的abs(int/double/float…):求绝对值
Arrays类:数组工具类
binarySearch(int[]/byte[]/char[]/double[]…,int key):二分搜索法
sort(int[]/byte[]/char[]/double[]) :给数组排序的(默认升序排序)
class FunctionDemo{
public static void main(String[] args){
//调用方法
int result = sum(10,20) ;
System.out.println("result:"+result) ;
System.out.println("----------------------") ;
//int result2 = sum2(10,20,30) ;
int result2 = sum(10,20,50) ;
System.out.println("result2:"+result2) ;
System.out.println("----------------------") ;
//int result3 = sum3(10,20,30,40) ;
int result3 = sum(10,20,50,60) ;
System.out.println("result3:"+result3) ;
}
//求两个数据之和!
public static int sum(int a,int b){
return a + b ;
}
//求三个数据之和
//public static int sum2(int a, int b,int c){//方法名相同
public static int sum(int a,int b,int c){
return a + b + c ;
}
//求四个数据之和
//public static int sum3(int a,int b,int c,int d){
public static int sum(int a,int b,int c,int d){
return a + b + c + d ;
}
}
需求:
比较两个数据是否相等,可以是byte类型,short,int类型…
方法重载(Overload) 和 方法重写(Override)的区别? 方法重写:在面向对象:继承中将
class FunctionTest{
public static void main(String[] args){
//定义两个变量
int a = 10 ;
int b = 20 ;
boolean flag = compare(a,b) ;
System.out.println(flag) ;
System.out.println("---------------------------") ;
byte m = 100 ;
byte n = 100 ;
boolean flag2 = compare(m,n) ;
System.out.println(flag2) ;
}
//compare:方法重载
public static boolean compare(byte m,byte n){
return m == n ;
}
//定义比较的方法
public static boolean compare(int a,int b){
return a == b;
}
}