定义格式:
public static void 方法名() {
//方法体;
}范例:
public static void method() {
//方法体;
}调用格式:
方法名();范例:
method() ;注意: 方法必须先定义,后调用,否则程序将报错
// 设计一个方法打印两个数中的最大数字
public class demo {
public static void main(String[] args) {
//在main()方法中调用定义好的方法
getMax();
}
//定义一个方法,用于打印两个数字中的较大数,例如getMax()
public static void getMax() {
//方法中定义两个变量,用于保存两个数字
int a = 10;
int b = 20;
//使用分支语句分两种情况对两个数字的大小关系进行处理
if(a > b) {
System.out.println(a);
} else {
System.out.println(b);
}
}
}//单参数
public static void 方法名 (参数1) {
//方法体;
}
//多参数
public static void 方法名 (参数1, 参数2, 参数3...) {
//方法体;
}public static void isEvenNumber(int number){
...
}
public static void getMax(int num1, int num2){
...
}注意:
调用格式:
方法名(参数);
方法名(参数1,参数2);范例:
isEvenNumber(10);
getMax(10,20);// 设计一个方法打印两个数中的最大数字
public class demo {
//定义一个方法,用于打印两个数字中的较大数,例如getMax()
//为方法定义两个参数,用于接收两个数字
public static void getMax(int a, int b) {
//使用分支语句分两种情况对两个数字的大小关系进行处理
if(a > b) {
System.out.println(a);
} else {
System.out.println(b);
}
}
public static void main(String[] args) {
//在main()方法中调用定义好的方法(使用常量)
getMax(10,20);
/**
调用方法的时候,人家要几个,你就给几个,人家要什么类型的,你就给什么类型的
这里是 int型,所以要传 int 类型的常量或变量 ,
10 不能是 10.0,20不能是20.0,否则会报错
*/
//在main()方法中调用定义好的方法(使用变量)
int a = 10;
int b = 20;
getMax(a, b);
}
}public static 数据类型 方法名 ( 参数 ) {
return 数据 ;
}public static boolean isEvenNumber( int number ) {
return true ;
}
public static int getMax( int a, int b ) {
return 100 ;
}方法名 ( 参数 ) ;
数据类型 变量名 = 方法名 ( 参数 ) ;isEvenNumber ( 5 ) ;
boolean flag = isEvenNumber ( 5 );// 设计一个方法打印两个数中的最大数字
public class demo {
//定义一个方法,用于获取两个数字中的较大数
public static int getMax(int a, int b) {
//使用分支语句分两种情况对两个数字的大小关系进行处理
//根据题设分别设置两种情况下对应的返回结果
if(a > b) {
return a;
} else {
return b;
}
}
public static void main(String[] args) {
//在main()方法中调用定义好的方法并使用变量保存
int result = getMax(10,20);
System.out.println(result);
//在main()方法中调用定义好的方法并直接打印结果
System.out.println(getMax(10,20));
}
}public class Demo {
public static void main(String[] args) {
}
public static void method_1() {
public static void method_2() {
// 这里会引发编译错误!!!
}
}
}public class Demo {
public static void method() {
//return 100; 编译错误,因为没有具体返回值类型
return;
//return语句后面不能跟数据或代码
}
public static void main(String[] args) {
}
}public static 返回值类型 方法名(参数) {
//方法体;
return 数据 ;
}public class Demo {
public static void fn(int a) {
//方法体
}
public static int fn(double a) {
//方法体
}
}
public class Demo {
public static float fn(int a) {
//方法体
}
public static int fn(int a , int b) {
//方法体
}
}