方法的声明
语法格式:
访问修饰符 返回类型 方法名(参数列表){
方法体
}
如:
public static 表示静态的方法 void表示不返回任何类型的值 main方法名
public static void main(String[] args) {
System.out.println("我是一个方法");
}
方法分为四类:
无参无返回值
public class helloDamo {
public void myDemo(){
System.out.println("***********");
}
public static void main(String[] ages){
//使用myDemo()这个方法
helloDamo newMy=new helloDamo();
newMy.myDemo();
System.out.println("欢迎来到java");
newMy.myDemo();
}
无参有返回值
例子:求长方形的面积
public class helloDamo {
public int myIntmath(){
int length=10;
int width=5;
int myArra=length*width;
return myArra;
}
public static void main(String[] ages){
helloDamo newMy=new helloDamo();
System.out.println(newMy.myIntmath()); //50
}
}
带参无返回值
例子:定义一个求两个float类型最大值的方法并打印出来
public class helloDamo {
public void max(float a,float b){
float max;
if(a>b){
max=a;
}else{
max=b;
}
System.out.println(max); //30.0
}
public static void main(String[] ages){
helloDamo newMy=new helloDamo();
float a=10,b=30;
newMy.max(a,b);
}
}
带参带返回值
例子:求1!+2!+3!+4!+5!=(1+1*2+1*2*3+1*2*3*4+1*2*3*4*5=)
public class helloDamo {
public int fax(int n){
int s=1;
for(int i=1;i<=n;i++){
s=s*i;
}
return s;
}
public static void main(String[] ages){
helloDamo newMy=new helloDamo();
int sum=0;
for(int n=1;n<=5;n++){
sum=sum+newMy.fax(n); //newMy.fax(1)把1代入上面的方法
}
System.out.println(sum); //1!+2!+3!+4!+5!=153
}
数组的方法
1. 打印数组内容
public class helloDamo {
public void arrAra(int[] arr){
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]); //2 3 8 5 10
}
System.out.println();
}
public static void main(String[] ages){
helloDamo newMy=new helloDamo();
int[] arr={2,3,8,5,10};
newMy.arrAra(arr);
}
2.查找数组是否含有某个元素
public class helloDamo {
public boolean mainArr(int[] arr,int n){
boolean flag=false;
for(int i=0;i<arr.length;i++){
if(arr[i]==n){
flag=true;
break;
}
}
return flag;
}
public static void main(String[] ages){
helloDamo newMy=new helloDamo();
int[] arr={2,3,8,5,10};
int n=3;
boolean flag=newMy.mainArr(arr,n);
if(flag){
System.out.println("找到了");
}else {
System.out.println("没找到!");
}
}
方法重载
定义:方法名相同,参数列表不同(可以是数据类型不同和参数数量不同)
int,double,数组 分别累加和
public class MathDemo {
//求两个int的和
public int puls(int a,int b){
return a+b;
}
//求两个double的和
public double puls(double n,double m){
return n+m;
}
//求数组元素的和
public int puls(int[] arr){
int sum=0;
for(int i=0;i<arr.length;i++){
sum=sum+arr[i];
}
return sum;
}
public static void main(String[] ages){
MathDemo myDemo=new MathDemo();
int a=5,b=10;
double n=20.3,m=6.7;
int[] arr={2,5,2,8};
System.out.println(myDemo.puls(a,b)); //15
System.out.println(myDemo.puls(n,m)); //27.0
System.out.println(myDemo.puls(arr)); //17
}
}
可变参数
查找数组是否含有某个元素,注:可变参数列表在方法重载,是所有方法中最后被调用的
public class ArgsDemo {
public void search(int m,int... n){
boolean foat=false;
for (int i:n){
if(i==m){
foat=true;
break;
}
}
if(foat){
System.out.println("找到啦!");
}else {
System.out.println("里面没有这个数哦");
}
}
public static void main(String[] ages){
ArgsDemo myDemo=new ArgsDemo();
int a=6;
int[] b={2,6,8,10};
myDemo.search(a,b);
}
}