Java实例——Java方法

转:https://www.runoob.com/java/java-examples.html

Java实例——Java方法

1、方法重载

方法重载——有时候需要使用相同的方法,得出不一样的结果。
在同一类当中,调用方法的时候,会发现:有很多方法名一样,但是参数不一样的方法。由此:

【1】方法名相同
【2】方法的参数类型或者参数个数不一样

//这两点是必须的。

【3】方法的返回类型可以不相同
【4】方法的修饰符可以不相同
【5】main方法也可以被重载——main()是普通方法

//但是虚拟机只调用带字符串公共类型的方法;
如果需要执行其他main方法,或者其他方法,都在
public static void main(String[] args) {}中调用。

public class Test01 {
	//重载,方法名相同
	int i;
	Test01(){
		System.out.println("无参数构造函数");
        i = 4;
	}
	Test01(int j){
		System.out.println("有参数构造函数");
        i = j;
	}
	public void add() {
		System.out.println("--------one----------");
	}
	public int add(int a,int b) {
		System.out.println("--------two----------"+(a+b));
		return a+b;		
	}
	public int add(int a,int b,int c) {
		System.out.println("--------three----------"+(a+b+c));
		return a+b+c;
	}
	/*public int add(int b,int a) {//方法重复,参数名转换顺序不行,冲突add(int,int) 
		return b;
	}*/
	public double add(int a,double b) {
		System.out.println("--------four----------"+(a+b));
		return a+b;
	}
	/*public int add(int a,double b) {//方法重复,与修饰符无关,int,double可换可不换,冲突add(int,double) 
		return a;		
	}*/
	
	public static void main(String[] args) {
		Test01 t1 =new Test01(4);
		t1.add();
		t1.add(1, 2.0);
		//重载构造函数
		new Test01();
	}
}
执行结果:
有参数构造函数
--------one----------
--------four----------3.0
无参数构造函数

2、输出数组元素

通过重载 printArray 方法输出不同类型(整型, 双精度及字符型)的数组

	//输出整型数组
	public static void printArray(Integer[] arr) {
		for(Integer i:arr) {
			System.out.print(i+"\t");
		}
	}
	//输出双精度数组
	public static void printArray(Double[] arr) {
		for(Double i:arr) {
			System.out.print(i+"\t");
		}
	}
	//输出字符型数组
	public static void printArray(Character[] arr) {
		for(Character i:arr) {
			System.out.print(i+"\t");
		}
	}
	public static void main(String[] args) {
		// 方法重载
		//使用重载输出数组元素
		 Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };
	     Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
	     Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' };
	     System.out.println("输出整型数组:");
	     printArray(integerArray);
	     System.out.println("\n输出双精度型数组:");
	     printArray(doubleArray);
	     System.out.println("\n输出字符型数组:");
	     printArray(characterArray);
	}
执行结果:
输出整型数组:
1	2	3	4	5	6	
输出双精度型数组:
1.1	2.2	3.3	4.4	5.5	6.6	7.7	
输出字符型数组:
H	E	L	L	O	

3、汉诺塔算法

【1】三根柱子,分别为x,y,z;n个碟子
【3】
先将上面n-1个盘子移动到y上;
以z为辅助柱,将1~n-1个盘子从x转移到y,
如果只有一个,直接从x——>z;
n才可以从x——>z;
然后以x为辅助柱,将1~n-1个盘子从y转移到z。

	private static void doTwers(int n, String from, String inter, String to) {
		if(n==1) {
			System.out.println("Disk 1 from"+from +" to "+to);
		}
		else {
			doTwers(n-1,from,to,inter);//1~n-1:x——>y
			System.out.println("Disk "+n +" from "+from +" to "+to);
			doTwers(n-1,inter,from,to);//1~n-1:y——>z
		}	
	}
		//汉诺塔算法
		int n=3;
		doTwers(n,"X","Y","Z");
执行结果:
Disk 1 fromX to Z
Disk 2 from X to Y
Disk 1 fromZ to Y
Disk 3 from X to Z
Disk 1 fromY to X
Disk 2 from Y to Z
Disk 1 fromX to Z

4、斐波那契数列

斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368……
第0项是0,第1项是第一个1。
这个数列从第三项开始,每一项都等于前两项之和。

	//斐波那契数列
	private static long fibonacci(long i) {
		if((i==0) || (i==1)) {
			return i;
		}else
			return fibonacci(i -1)+fibonacci(i -2);
	}
	//斐波那契数列
		for(int i=0;i<=10;i++) {
			System.out.printf("Fibonacci of %d is: %d\n",i,fibonacci(i));
		}
执行结果:
Fibonacci of 0 is: 0
Fibonacci of 1 is: 1
Fibonacci of 2 is: 1
Fibonacci of 3 is: 2
Fibonacci of 4 is: 3
Fibonacci of 5 is: 5
Fibonacci of 6 is: 8
Fibonacci of 7 is: 13
Fibonacci of 8 is: 21
Fibonacci of 9 is: 34
Fibonacci of 10 is: 55

5、阶乘

一个正整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积,并且有0的阶乘为1。自然数n的阶乘写作n!。

	//阶乘
	private static long factorial(int i) {
		if(i <=1)
			return 1;
		else
		    return i * factorial(i-1);
	}
		//阶乘
		for(int i=0;i<=10;i++) {
	  	System.out.printf("%d! is: %d\n",i,factorial(i));
	     }
执行结果:
0! is: 1
1! is: 1
2! is: 2
3! is: 6
4! is: 24
5! is: 120
6! is: 720
7! is: 5040
8! is: 40320
9! is: 362880
10! is: 3628800

6、 方法覆盖(继承)

子类继承父类的方法,并且重写父类方法,调用该方法会直接覆盖父类的方法。

//父类
public class Bycle {
	int speed =20;
	public void speedUp() {
		this.speed =this.speed +10;
	}
}
//子类
public class Bycle01 extends Bycle{
	public void speedUp() {
		this.speed =this.speed*2;
	}
}

public static void main(String[] args) {
		Bycle b1 =new Bycle01();
	    System.out.println(b1.speed);
	    
	    Bycle b2 =new Bycle();
	    System.out.println(b2.speed);
}
执行结果:
40  //子类方法
30  //父类方法

7、instanceof 关键字用法

instanceof 是 Java 的一个二元操作符,类似于 ==,>,< 等操作符。
instanceof 是 Java 的保留关键字。它的作用是测试它左边的对象是否是它右边的类的实例,返回 boolean 的数据类型。

		//instanceof 关键字用法
		Object o =new ArrayList();
		Object o2 =6;
		String str1 =(o instanceof ArrayList)==true? "是":"不是";
		String str2 =(o2 instanceof Integer)==true? "是":"不是";
		System.out.printf("对象 o 是 java.util.Vector 类的实例吗?  "+str1);
		System.out.printf("\n对象 %d 是 java.lang.Integer类的实例吗?  "+str2,o2);
执行结果:
对象 o 是 java.util.Vector 类的实例吗?  是
对象 6 是 java.lang.Integer类的实例吗?  是

8、break 关键字用法

Java break 语句可以直接强行退出当前的循环,忽略循环体中任何其他语句和循环条件测试。

		//break 关键字用法
		int[] arr = {11,12,34,34,46,68,25,23,34,67,58,5678};
		int no =34;
		int i=0;
		boolean found =false;
		for(;i<arr.length;i++) {
			if(arr[i] == no) {
				found =true;
				break;//不写输出34 元素的索引位置在: 12
			}
		}
		if(found) {
			 System.out.println(no + " 元素的索引位置在: " + i);
		} else {
            System.out.println(no + " 元素不在数组中");
        }
		System.out.println("数组的长度为:"+arr.length);
执行结果:
34 元素的索引位置在: 2
数组的长度为:12

9、continue 关键字用法

Java continue 语句语句用来结束当前循环,并进入下一次循环,即仅仅这一次循环结束了,不是所有循环结束了,后边的循环依旧进行。

		//continue 关键字用法
		StringBuffer buffer =new StringBuffer("hello how are you");
		int length =buffer.length();
		int count =0;
		for(int i=0;i<length;i++) {
			if(buffer.charAt(i) !='h') 
				continue;
				count++;//不符合条件,跳出循环执行
				buffer.setCharAt(i,'o');
				
		}
		System.out.println("发现 " + count 
		        + " 个 h 字符");
		 System.out.println(buffer);
执行结果:
发现 2 个 h 字符
oello oow are you

10、标签(Label)

Java 中的标签是为循环设计的,是为了在多重循环中方便的使用break 和coutinue 。

		//标签(Label)
		String str1 ="This is the string in which you have to search for a substring";
		String str2 ="substring";
		boolean found =false;
		int max =str1.length() - str2.length();//遍历次数
		testb1://标签
			for(int i=0;i<=max;i++) {//遍历str1的元素
				int length =str2.length();//子字符串的长度
				int j = i;
				int k = 0;
				while(length-- != 0) {
					if(str1.charAt(j++) != str2.charAt(k++)) {//一一对应
						continue testb1;
					}
				}
				found = true;
				break testb1;
			}
		if(found) {
			System.out.println("发现子字符串。");
		}else {
			System.out.println("字符串中没有发现子字符串。");
		}
执行结果;
发现子字符串。

11、enum 和 switch 语句使用

enum——包含所有关键字
switch——选择条件

enum Car {
    lamborghini,tata,audi,fiat,honda
}
public class Main {
    public static void main(String args[]){
        Car c;
        c = Car.tata;
        switch(c) {
            case lamborghini:
                System.out.println("你选择了 lamborghini!");
                break;
            case tata:
                System.out.println("你选择了 tata!");
                break;
            case audi:
                System.out.println("你选择了 audi!");
                break;
            case fiat:
                System.out.println("你选择了 fiat!");
                break;
            case honda:
                System.out.println("你选择了 honda!");
                break;
            default:
                System.out.println("我不知道你的车型。");
                break;
        }
    }
}
执行结果:
你选择了 tata!

12、Enum(枚举)构造函数及方法的使用

	//枚举
	enum Car{
		lamborghini(900),tata(2),audi(50),fiat(15),honda(12);
		private int price;
		Car(int p){
			price =p;
		}
		int getPrice() {
			return price;
		}
	}
		System.out.println("所有汽车的价格:");
		for(Car c: Car.values()) {
			 System.out.println(c + " 需要 "  + c.getPrice() + " 千美元。");
		}
执行结果:
所有汽车的价格:
lamborghini 需要 900 千美元。
tata 需要 2 千美元。
audi 需要 50 千美元。
fiat 需要 15 千美元。
honda 需要 12 千美元。

13、 for 和 foreach循环使用

for 语句比较简单,用于循环数据。
for循环执行的次数是在执行前就确定的。
foreach语句是java5的新特征之一,在遍历数组、集合方面,foreach为开发人员提供了极大的方便。

14、Varargs 可变参数使用(需要输入多个参数,不确定)

定义实参个数可变的方法:只要在一个形参的"类型"与"参数名"之间加上三个连续的"."(即"…",英文里的句中省略号),就可以让它和不确定个实参相匹配。

	//Varargs 可变参数使用
	private static int sumArgs(int...args) {
		int sum = 0,i;
		for(i=0;i<args.length;i++) {
			sum += args[i];
		}
		return sum;
	}
		//Varargs 可变参数使用
		int sum =0;
		sum =sumArgs(new int[] {1,2,3,4,5});
		System.out.println("数字相加之和为:"+sum);
执行结果:
数字相加之和为:15

15、重载(overloading)方法中使用 Varargs

	//vaTest——int
	private static void varTest(int...args) {
		System.out.println("--------------int-------------");
		for(int n:args) {
			System.out.print(n+"\t");
		}	
	}
	//vaTest——String
	private static void varTest(String...args) {
		System.out.println("--------------String-------------");
		for(String n:args) {
			System.out.print(n+"\t");
		}	
	}
	//vaTest——boolean
	private static void varTest(boolean...args) {
		System.out.println("--------------boolean-------------");
		for(boolean n:args) {
			System.out.print(n+"\t");
		}	
	}
		//重载(overloading)方法中使用 Varargs
		varTest(1,2,3);
		System.out.println();
		varTest("1","2","3");
		System.out.println();
		varTest(true,true,false);
执行结果:
--------------int-------------
1	2	3	
--------------String-------------
1	2	3	
--------------boolean-------------
true	true	false	
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值