自定义函数

自定义函数
     语法:
     修饰符     返回值类型     函数名(形式参数列表){
               代码块|函数体
     }
例如:
          public static int max(int a,int b){
               if(a>b)
                    return a;
               else
                    return b;
          }
上面实例中,修饰符有public和static两个关键字
public static声明的函数是公共的,静态函数,方便在类的内部调用。
 
返回值类型:是指函数的返回值的数据类型,如果没有返回值,声明void
 
返回值是函数调用者获得一个结果,用return关键字返回值,这个值是什么类型,函数就定义位这个类型。
一个函数只能有一个返回值,
return 语句后不能有其他语句。
 
 
形式参数列表,用于函数接收调用传入的数据。形式参数声明类型似于变量。
 
 
调用静态(static)函数:
     如果非void函数:变量  = 函数名(实参)
     如果void函数:函数名(实参)
          

/**
猜数字
*/
import java.util.*;
public class Demo2{
/*
比较两个数的大小关系
返回0表示相等,返回1表示第一个参数大于第二参数,返回返回-1
*/
public static int compare(int n1, int n2){
if(n1>n2)
return 1;
else if(n1<n2)
return -1;
else
return 0;
}
 
/*
功能:计数
参数:当前次数
返回值:计数后的新的结果
*/
public static int count(int num){
int t;
 t = num+1;
return t;
}
 
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
Random rand = new Random();
int num = rand.nextInt(90)+10;//随机数10-100的整数
 
int times = 0;//记录猜数的次数
while(true){
System.out.print("请猜大小:");
int guess = kb.nextInt();
//调用计数函数
times = count(times);
 
int rs = compare(guess,num);//调用比大小
if(rs>0)
System.out.println("大了");
else if(rs<0)
System.out.println("小了");
else
break;
}
 
System.out.println("猜中了,共花了"+times+"次机会.");
 
}
}
 

/**
    函数的调用
*/
public class Demo5{
    public static void fun1(int a){
        System.out.println(a*a);
    }
    public void fun2(int a){
        System.out.println(a*a*a);
    }
 
    public static void main(String[] args){
        int n=10;
        fun1(n);//静态方法内调用静态方法
 
        //fun2(10);//错误: 无法从静态上下文中引用非静态 方法 fun2(10)
        //正确调用非静态方法
        new Demo5().fun2(10);
        //
        Demo5 d = new Demo5();
        d.fun2(10);
    }
}
 
 
原文地址:https://www.cnblogs.com/zachary7/p/8191397.html