一、何为方法
1. System.out.println()
:在System类中调用对象out下的println()方法
//用方法实现加法,并在主方法中调用
package Practice;
public class Prac{
//需要返回一个int类结果
public static int add(int a,int b){
return a+b;
}
//调用主方法
public static void main(String[] args) {
int add = add(1,2);
System.out.println(add);
}
}
2. public static void test()
:void表示返回空
Code:
package Practice;
public class Prac{
//main方法调用test方法并执行
public static void main(String[] args) {
Prac prac = new Prac();
prac.test();
}
//test方法用于输出0到5
public void test(){
for(int i=0;i<6;i++){
System.out.println(i);
}
}
}
输出:
0
1
2
3
4
5
Process finished with exit code 0
二、实例
int类数值比大小
package Practice;
import java.util.Scanner;
public class Prac{
public static void main(String[] args) {
//输出两个int类数值
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
//调用Prac中的max()函数
Prac prac = new Prac();
System.out.println(prac.max(a,b));
}
//max函数
public int max(int a,int b){
int result = 0;
if (a>b){
result = a;
}
else if (a==b){
System.out.println("相等");
return 0; //终止方法
}
else{
result = b;
}
return result;
}
}
三、方法重载
以上述实例为例,两个相同名称(max)方法,处理的类不同(double int)可同时自动区分调用。
package Practice;
import java.util.Scanner;
public class Prac{
public static void main(String[] args) {
Prac prac = new Prac();
Scanner scanner = new Scanner(System.in);
//int a = scanner.nextInt();
//int b = scanner.nextInt();
double a = scanner.nextInt();
double b = scanner.nextInt();
//Prac.max(a,b);
System.out.println(prac.max(a,b));
}
public int max(int a,int b){
int result = 0;
if (a>b){
result = a;
}
else if (a==b){
System.out.println("相等");
return 0; //终止方法
}
else{
result = b;
}
return result;
}
public double max(double a,double b){
double result = 0;
if (a>b){
result = a;
}
else if (a==b){
System.out.println("相等");
return 0; //终止方法
}
else{
result = b;
}
return result;
}
}
四、可变参数
语法:public void 方法名(数据类型... 数组命名)
一个方法中只能指定一个可变参量,而且必须放在最后
实例:找出一个数组中的最大值
package Practice;
import java.util.Scanner;
public class Prac{
public static void main(String[] args) {
Prac prac = new Prac();
prac.printMax(35.0,44.0,2.0,3.4,5.0);
}
public void printMax(double... numbers){
if (numbers.length == 0){
System.out.println("No argument passed");
return;
}
double result = numbers[0];
//排序!!
for (int i = 1;i < numbers.length;i++){
if (numbers[i]>result){
result = numbers[i];
}
}
System.out.println(numbers.length);
System.out.println("The max value is " + result);
}
}
五、递归
很重要,但能不用递归就不用递归
A方法调用A方法,自己调用自己
结构:
- 递归头:什么时候不调用自身方法(如果没有头,会陷入死循环)
- 递归体:什么时候调用自身方法
实例:阶乘
package Practice;
import java.util.Scanner;
public class Prac{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("请输入要计算的阶乘数");
int n = scanner.nextInt();
Prac prac = new Prac();
long result = prac.calc(n);
System.out.println("结果为" + result);
}
//阶乘
public int calc(int n){
if (n == 1){
return 1;
}else{
return n = n*calc(n-1); //调用自己
}
}
}
输出:
请输入要计算的阶乘数
5
结果为120
Process finished with exit code 0
注意int的内存溢出!!