零基础学java---方法(2)

方法

3.带参数方法的定义和调用

3.3形参和实参

形参:方法定义中的参数

            相当于变量定义格式,例int number

实参:方法调用中参数

           等同于变量或常量,例如10   , number

3.4 带参数方法练习

需求: 设计一个方法用于打印两个数中最大数,数据来自于方法参数

思路:

1.定义一个方法,用于打印两个书中的最大数,例如getMax()

public static void getMax( ){

}

2.为方法定义两个参数,用于接收数据

 public static void getMax(int a,int b){

}

3.使用分支语句分两种情况对数字的大小关系进行处理;

if (a>b){

          system.out.println(a);

}else{

          system.out.printf(b);

4.在main方法中调用定义好的方法(使用常量

public static void main(String[ ] args){

//直接传递常量

          getMax(10,20);

}

5.在main方法中调用定义好的方法(使用变量

public static void main(String[ ] args){

//定义变量,传递

        int a=10;

        int b=20;

        getMax(a,b);

}

代码示例:

public static void main(String[] args) {
		// TODO Auto-generated method stub
		getMax(10, 20);//使用常量
		int a=10;
		int b=20;
		getMax(a, b);//使用变量
	}

	public static void getMax(int a,int b){
		if (a>b){
			System.out.println(a);
		}else{
			System.out.println(b);
		}
	}

4.带返回值的方法的定义和调用

4.1 带返回值的方法定义

格式:public static 数据类型       方法名参数){

           return 数据;

}

范例: public static boolean isEvenNumber(int number){

              return true;

}

范例2:public static int getMax(int a,int b){

             return 100;    

 }

注意:方法定义时return 后面的返回值与方法定义上的数据类型相匹配,否则程序报错

4.2带返回值的方法调用

格式: 方法名(参数);

范例:isEvenNumber(5);

格式2:数据类型  变量名  =  方法名(参数);

范例:boolean   Number   =  isEvennumber(5);

注意:

方法的返回值通常会使用变量接收,否则该返回值将无意义

示例代码:定义一个方法,该方法接收一个参数,判断该数据是否为偶数,并返回true or false

public static void main(String[] args) {
		//数据类型 变量名 = 方法名(参数)
		boolean flag= isEvenNumber(10);
		System.out.println(flag);
	}
	public static boolean isEvenNumber(int number) {
		if(number%2==0){
			return true;
		}else{
			return false;
		}
	}

明天更后续,觉得不错的留个赞,点个关注,期待后续.....

猜你喜欢

转载自blog.csdn.net/m0_68089732/article/details/123961748