方法:完成特定功能的代码块,在很多语言中有函数的定义,在Java中函数被称为方法。
格式:修饰符 返回值类型 方法名(参数类型 参数名1,参数类型 参数名2,.....)
{
方法体语句;
return返回值;
}
注意事项:A:方法不调用不执行
B:不能嵌套定义方法
例:不能在一个public static里面再定义一个public static方法
C:方法定义的时候参数之间用逗号隔开
D:方法调用的时候不用传递数据类型
E:如果方法有明确返回值,一定要有return带回一个值执行
执行特点:不调用,不执行
例:
不调用:
没有调用,运行成功但输出没有结果,main方法被jvm运行。
调用:
方法相关例题:
键盘录入两数据,返回两个数中的最大值
1 import java.util.Scanner; 2 3 public class Test{ 4 public static void main(String[] args) { 5 @SuppressWarnings("resource") 6 Scanner sc = new Scanner(System.in); 7 8 System.out.println("请输入第一个数:"); 9 int a = sc.nextInt(); 10 11 System.out.println("请输入第二个数:"); 12 int b = sc.nextInt(); 13 14 int result = getMax(a,b); 15 System.out.println("较大值是:"+result); 16 } 17 public static int getMax(int a, int b) { 18 //if语句 19 /*if(a>b) { 20 return a; 21 }else { 22 return b; 23 }*/ 24 //三元 25 return ((a>b)? a:b); 26 } 27 }
键盘录入两数据,两个数相加
1 public class Test { 2 public static void main(String[] args) { 3 int x = 10; 4 int y = 20; 5 int result = sum(x,y); 6 System.out.println(result); 7 } 8 9 10 public static int sum(int a , int b) { 11 return(a+b); 12 } 13 }
键盘录入两数据,判断两数是否相等
1 import java.util.Scanner; 2 3 public class Test{ 4 public static void main(String[] args) { 5 @SuppressWarnings("resource") 6 Scanner sc = new Scanner(System.in); 7 System.out.println("请输入第一个数:"); 8 int a = sc.nextInt(); 9 10 System.out.println("请输入第一个数:"); 11 int b = sc.nextInt(); 12 13 boolean flag = compare(a,b); 14 System.out.println(flag); 15 } 16 public static boolean compare(int a, int b) { 17 //if语句 18 /*if(a == b) { 19 return(true); 20 }else { 21 return(false); 22 }*/ 23 //三元 24 /*boolean flag = ((a==b) ? true:false); 25 return flag;*/ 26 //最终版 27 return a==b; 28 } 29 }
键盘录入一个数据n(1<=n<9),输出对应的nn乘法表
1 import java.util.Scanner; 2 3 public class Test{ 4 public static void main(String[] args) { 5 @SuppressWarnings("resource") 6 Scanner sc = new Scanner(System.in); 7 8 System.out.println("请输入一个数n:"); 9 int n = sc.nextInt(); 10 11 printChenfa(n); 12 13 } 14 public static void printChenfa(int n) { 15 for(int x=1; x<=n;x++) { 16 for(int y=1; y<=x; y++) { 17 System.out.print(y+"*"+x+"="+y*x+"\t"); 18 } 19 System.out.println(); 20 } 21 } 22 }
原文:https://www.cnblogs.com/dongjiaonakeshu/p/13975179.html