导读
1.方法声明的格式,分类及实例运用
2.数组作为参数的传值问题
3.可变参数列表
4.带可变参数的方法重载与帮助文档
5.一个工具类 Arrays
方法声明的格式,分类及实例运用
package hala1;
public class hello {
public void swap(int a,int b){
int temp;
System.out.println("交换前:a="+a+" b="+b);
temp=a;a=b;b=temp;
System.out.println("交换后:a="+a+" b="+b);
}
public void swapTest(){
int m=4,n=5;
System.out.println("交换前:m="+m+" n="+n);
swap(m,n);//两个方法在同一个类中调用时直接写方法名即可
System.out.println("交换后:m="+m+" n="+n);
}
public static void main(String[] args) {
hello h=new hello();//在主方法中调用其他方法,要先声明类
h.swapTest();
}
//这里输出的结果可以看出方法里的值并不能传到外边,这里与c语言一致
}
输出结果
交换前:m=4 n=5
交换前:a=4 b=5
交换后:a=5 b=4
交换后:m=4 n=5
数组作为参数的传值问题
package hala1;
public class hello {
public void updateArray(int[] a){//数组做参数的格式
a[3]=15;
System.out.print("数组a的元素的值为:");
for(int n:a){
System.out.print(n+" ");
}
System.out.println();
}
public static void main(String[] args) {
hello h=new hello();//在主方法中调用其他方法,要先声明类
int[] a1={1,2,3,4,5};
System.out.print("方法调用前数组的值");
for(int n:a1){
System.out.print(n+" ");
}
System.out.println();
h.updateArray(a1);
System.out.print("方法调用后数组的值");
for(int n:a1){
System.out.print(n+" ");
}
System.out.println();
}
//这里数组的值真的被改变了,与一般参数不一样,是因为数组是引用类型,是管理者而非拥有者
}
输出结果
方法调用前数组的值1 2 3 4 5
数组a的元素的值为:1 2 3 15 5
方法调用后数组的值1 2 3 15 5
可变参数列表
package hala1;
public class hello {
public void search(int n,int... a){
//可变参数列表,若有多个,一定要写在最后
boolean flag=false;
for(int a1:a){
if(a1==n){
flag=true;
break;
}
}
if(flag){
System.out.println("找到了!"+n);
}
else{
System.out.println("没找到!"+n);
}
}
public static void main(String[] args) {
hello h=new hello();
h.search(3,1,2,3,4,5);
int a[]={1,2,3,4,5};
h.search(3, a);
//可变参数传值时,可以用一般形式,也可以用数组
//可变参数与数组有着微妙的联系,如果重载search为数组,如下:
//public void search(int n,int[] a) 此时会报错
//但如果先定义了数组方法,再定义可变参数方法,则不会报错
}
}
输出结果
找到了!3
找到了!3
带可变参数的方法重载与帮助文档
package hala1;
/**
* @version
* @author air
*这里为帮助文档,输入/**加回车,此外还可以表明作者和版本号
*/
public class hello {
public int plus(int a,int b){
System.out.println("不带可变参数的方法被调用!");
return a+b;
}
public int plus(int b,int... a){
int sum=0;
for(int a1:a){
sum+=a1;
}
sum+=b;
System.out.println("带可变参数列表的方法被调用!");
return sum;
}
public static void main(String[] args) {
hello h=new hello();
System.out.println("和为:"+h.plus(1, 2));
//带可变参数的方法会被最后调用,如果有其他方法符合则不会被调用
//这里输出结果可以发现,先输出方法里边的句子,在输出主方法里边的句子,最后输出方法返回值
}
}
输出结果
不带可变参数的方法被调用!
和为:3