方法进阶.

方法格式

public static void 方法名()
{
	方法体
}	
调用格式

方法名称();
package miao;

public class hello
{
	public static void main(String[] args)
	{
		PrintMethod();
	}

	public static void PrintMethod()
	{
		for (int i = 0; i < 5; i++)
		{
			for (int j = 0; j < 20; j++)
			{
				System.out.print("*");
			}
			System.out.println("*");
		}
	}
}

结果打印:20X5的 长方形*号矩阵;
方法不能嵌套
定义方法不能自己执行,需有main方法的地方调用它执行;

方法定义格式

方法即 若干语句功能的集合。

参数(原料): 进入方法的数据;
返回值(产出物):方法中出来的数据;

定义方格式
修饰符  返回值类型 方法名称(参数类型 参数名称,。。。参数类型 参数名称)
{
		方法体
		return 返回值;
}

举例:

	public static void main(String[] args)	//主方法
	{
		
	}
	public static int sum(int a, int b)
	{
		int result = a + b;   //方法体
		return result;  //返回值需(result)和返回值类型(int)对应,均是int
	}

方法调用格式

1.单独调用

格式: 方法名称(参数)
只能执行方法,方法产生的结果无法使用

public static void main(String[] args) // 主方法
	{   
		//单独调用方法
		sum(10, 20);			//方法名称(参数)
		//打印调用方法
		System.out.println(sum(10, 20));   //System.out.println(方法名称(参数));
		//赋值调用方法
		int number = sum(15, 25);  //数据类型  变量名称 = 方法名称(参数)
		System.out.println(number);  
	}

	public static int sum(int a, int b)
	{
		System.out.println("方法执行");
		int result = a + b;
		return result;
	}

2.打印调用

格式: System.out.println(方法名称(参数));

3.赋值调用

数据类型 变量名称 = 方法名称(参数)

有返回值的不用void

案例1-100 所有和

public static void main(String[] args)
	{
		System.out.println(sum());
	}

	public static int sum()
	{
		int sum = 0;
		for (int i = 1; i <= 100; i++)
		{
			sum += i;
		}
		return sum;	
	}

案例判断两个数是否相同

public static void main(String[] args) 
	{   
		System.out.println(same(6, 6));
	}
		public static boolean same(int a, int b)
	{
		// boolean same; 第一种方法
		// if (a == b)
		// {
		// same = true;
		// } else
		// {
		// same = false;
		// }
		// return same;
		// }
		return a == b;    //第二种方法判断,表达式是布尔型
	}
}

案例打印指定次数helloworld

	public static void main(String[] args)
	{
		printCount(4);        
	}

	public static void printCount(int num)
	{
		for (int i = 1; i < num; i++)
		{
			System.out.println("hellworld");
		}
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值