JAVA学习第三课(函数及其重载)

switch()适用byte、short、int、char,string

如果case 中不加break,会一直执行,知道},或break,结束

如:


public class Main {


	public static void main(String[] args)
	{
		//int x = 5, y = 4,xx = 6;
		char a = 'f';
		switch(a)
		{
		default :System.out.println("d");
		case 'a':System.out.println("a");
		case 'b':System.out.println("b");break;
		case 'c':System.out.println("c");break;
		
		}
		
		
	//	System.out.println("56");
	}
}


执行结果是 d 、a、b


if与switch区别
if:
1.对具体的值进行判断
2.对区间进行判断
3.对运算结果是boolean类型的表达式进行判断


switch:
1.对具体的值进行判断
2.值的个数是固定的
PS:对于几个固定的值,最好使用switch,因为switch会一次性把具体的答案都加载进内存,效率相对较高
switch不大常用,功能性较差,且书写麻烦


在windows系统中回车符是 \r\n;
Linux系统是\n


函数:



函数的定义:


修饰符(public 可加可不加,起到一个权限的作用) 函数类型 函数名(参数类型 参数名,参数类型 参数名)

执行语句;
return 返回值;


import java.util.Scanner;


public class Main
{
	public static void main(String[] args)
	{
		Scanner cin = new Scanner(System.in);
		int n = cin.nextInt();
		int a = cin.nextInt();
		int ans = sum(n,a);
		System.out.println("ans = " +ans);
		int ans1 = sub(a,n);
		System.out.println("ans1 = "+ans1);
		cin.close();
	}
	static int sum(int a,int b)//不加public
	{
		return a+ b;
	}
	public static int sub(int a,int b) //加public
	{
		return a-b;
	}
	
}





函数的重载:

同函数名,参数类型不同,执行的功能特点一样,如:都是加,都是减,找最大

比较简单和特点C++基本相同


事例代码:

import org.omg.CosNaming.NamingContextExtPackage.AddressHelper;


public class Main 
{
	public static void main(String[] args)
	{
		int ans = add(4,5);
		int sum = add(5,6,7);
		System.out.println(ans);
		System.out.println(sum);
	}
	static int add(int x,int y)
	{
		return x +y;
	}
	static int add(int x,int y,int z)
	{
	//	return x + y + z;
		return add(x, y) + z;/*前面已经定义过的额函数,就可以进行调用,
		                      所以,函数重载,有一些重复的功能,可以互相调用*/
	}
	
}


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值