方法(也叫函数)
方法就是完成特定功能的代码块
方法格式:
修饰符 返回值类型 方法名(参数类型 参数名1,参数类型 参数名2…) {
函数体;
return 返回值;
}
方法的两个明确:
* A:返回值类型 明确功能结果的数据类型
* B:参数列表 明确有几个参数,以及参数的类型
练习:求两个数的和
public class MethodDemo {
/*
* 写一个方法,用于求和。 两个明确: 返回值类型 int 参数列表 int a,int b
*/
public static int sum(int a, int b) {
// int c = a + b;
// return c;
return a + b;
}
public static void main(String[] args) {
// 单独调用
// sum(10,20);
// 输出调用
// System.out.println(sum(10,20));
// 赋值调用
int s = sum(10, 20);
// s+=100;
System.out.println("s:"+s);
}
}
联系:键盘录入两个数据,返回两个数中的较大值
import java.util.Scanner;
/*
* 需求:键盘录入两个数据,返回两个数中的较大值
*
* 两个明确:
* 返回值类型:int
* 参数列表:int a,int b
*/
public class MethodTest {
// 返回两个数中的较大值
public static int getMax(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
public static void main(String[] args) {
//创建对象
Scanner sc = new Scanner(System.in);
//接收数据
System.out.println("请输入第一个数据:");
int x = sc.nextInt();
System.out.println("请输入第二个数据:");
int y = sc.nextInt();
//调用方法
int max = getMax(x,y);
System.out.println("max:"+max);
}
}
练习:键盘录入三个数据,返回三个数中的最大值
import java.util.Scanner;
/*
* 需求:键盘录入三个数据,返回三个数中的最大值
*
* 两个明确:
* 返回值类型:int
* 参数列表:int a,int b,int c
*/
public class MethodTest3 {
// 返回三个数中的最大值
public static int getMax(int a, int b, int c) {
if (a > b) {
if (a > c) {
return a;
} else {
return c;
}
} else {
if (b > c) {
return b;
} else {
return c;
}
}
}
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);
}
}
练习:打印1到n之间的数据
/*
* 需求:写一个方法,传递一个整数(大于1),在控制台打印1到该数据的值。
*
* 两个明确:
* 返回值类型:void
* 参数列表:int n
*/
public class MethodTest {
//在控制台打印1到该数据n的值
public static void printNumber(int n) {
for(int x=1; x<=n; x++) {
System.out.println(x);
}
}
public static void main(String[] args) {
printNumber(10);
System.out.println("-------------------");
printNumber(100);
}
}
练习:打印所有的水仙花数
/*
* 写一个方法,把所有的水仙花数打印在控制台
*
* 两个明确:
* 返回值类型:void
* 参数列表:无参数
*/
public class MethodTest2 {
//把所有的水仙花数打印在控制台
public static void printFlower() {
for(int x=100; x<1000; x++) {
int ge = x%10;
int shi = x/10%10;
int bai = x/10/10%10;
if((ge*ge*ge+shi*shi*shi+bai*bai*bai) == x){
System.out.println(x);
}
}
}
public static void main(String[] args) {
printFlower();
}
}