四、Java 基本函数

1 函数
2 函数的重载

1、函数

定义在类中的一段功能独立的程序,也叫方法格式
修饰符 返回值类型 名称 (参数类型 形参1,参数类型 形参2 ....) 
{
	执行语句
	return  返回值	
}
	
	函数可以调用函数,不可以嵌套定义
	
	java中最小的功能就是函数
	
	变量的作用域
	
	
	定义函数

	  public static void main(String[] args) 
		{						
			int x=90;
			float y=3.14f; 
			
			float result =add(x,y);
			System.out.println(result);	
		}
		
		//一个有返回值,有参数传入的函数,
		public static float add( int a, float b) //这里声明的参数,称为形参
		{
			float result= a+b;
			return result
		}
		
		
		//例子 铺地板的程序 (现有n块空地,要按行,列铺上地板,要分别铺不同形状的地板)		
	 public static void main(String[] args) 
		{
			int a=9;
			int b=10;
			String c="$";
			
			pudiban(9,10,"@"); 
			
			pudiban(5,5,"#"); 
			
			pudiban(3,8,"*"); 
			
			//pudiban(a,c,b);
			
		}
		static  void pudiban(int rows,int cols, String style){
			for (int i = 0; i < rows; i++) {
				for (int j = 0; j < cols; j++) {
					System.out.print(style);
				}
				System.out.println();
			}	
		}
				
	
	//例子 铺地板的程序 (现有n块空地,要按行,列铺上地板,要分别铺不同形状的地板)	,铺完地板后,把工钱算出来
					
    float money =pudiban(20,15,"%",3.5f);
		System.out.println("最后给你的工钱是" +money);		
		static float pudiban(int rows,int cols, String style,float money){
			for (int i = 0; i < rows; i++) {
				for (int j = 0; j < cols; j++) {
					System.out.print(style);
				}
				System.out.println();
			}
				
			return	rows*cols*money;
		}

  //一个函数,判断2个数是不是相同
		static boolean isSame(int a, int b) {
				/*
				 * if(a==b){ return true; } else{ return false; }
				 */
				return a == b;
			}
	  static boolean isSame(float a,float b){
			return a == b;
		}
			
		static int getDaysOfMonth(int month,int year){
		switch(month){
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			return 31;
		case 4:
		case 6:
		case 9:
		case 11:
			return 30;
		case 2:
			if(isLeapYear(year)){
				return 29;
			}
			else{
				return 28;
			}
	
		default:  //注意:这里不加defalut将会出错,因为不是所有的分支全返回了
			return -1;
		}
		
}

2、函数的重载

 同一个类中,允许有多个同名的函数,但是,其参数个数或参数类型不同 (函数的重载与函数的返回值无关)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值