方法的调用
1、有明确返回值:
1、键盘录入三个数据,返回三个数中的最大值
(1)首先使用导包,自定义输入
(2)调用方法
(3)返回值类型:int
(4)参数列表(int a,int b , int c )
(5)使用三元运算符
package Practice;
import java.util.Scanner;
public class pt1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个数:");
int a = sc.nextInt();
System.out.println("请输入第二个数:");
int b = sc.nextInt();
System.out.println("请输入第三个数:");
int c = sc.nextInt();
//调用
int max = getMax(a,b,c);
System.out.println("max="+max);
}
public static int getMax(int a, int b, int c) {
int max=(( (a>b) ? a:b)>c)? ( (a>b) ? a:b):c;
return max;
}
}
(6)最后返回最大值
2、键盘录入两个数据,比较两个数是否相等
返回值类型:boolean类型:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("s1:");
int m = sc.nextInt();
System.out.println("s2:");
int n = sc.nextInt();
//调用
boolean c= getEquals(m,n);
System.out.println("m=n:"+c);
}
public static boolean getEquals(int m, int n) {
return m==n;
}
2、没有明确返回值的方法调用
其实就是void类型方法的调用
只能单独调用
例如:键盘录入一个数据n(1<=n<=9),输出对应的nn乘法表
用"x”表示乘号
import java.util.Scanner;
public class pt3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个数:");
int n = scanner.nextInt();
//调用方法:
get(n);
}
public static void get(int n) {//void类型方法的调用没有明确返回值
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j+"x"+i+"="+i*j+" ");
}
System.out.println();
}
}
例如当输入n=9的时候就可以打印9x9乘法表
输出结果为:
请输入一个数:
9
1x1=1
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
1x4=4 2x4=8 3x4=12 4x4=16
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81
3、方法重载
在同一个类中,允许存在一个以上的同名方法,只要它们的参数个数或者参数类型不同即可。
例如:比较两个数据是否相等。参数类型分别为两个byte类型,两个short类型,两个int类型,两个long类型,并在main方法中进行测试
这边我们先测试一下byte和short类型:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("s1");
short a= scanner.nextShort();
System.out.println("s2");
short b = scanner.nextShort();
byte x= 23;
byte y = 43;
boolean m = getEquals(a,b);
boolean n = getEquals(x,y);
System.out.println("a和b是否相等:"+m);
System.out.println("x和y是否相等:"+n);
}
public static boolean getEquals(short a, short b) {
return a==b;
}
public static boolean getEquals(byte x, byte y) {
return x==y;
}
显然byte x 和 byte y不相等,我们自定义输出a=40.,b=40
s1
40
s2
40
a和b是否相等:true
x和y是否相等:false
返回值类型为boolean类型;