3. super家养了一对刚出生的兔子, 兔子出生3个月起每月都会生一对小兔子, 小兔子出生后三个月起也会每月生一对兔子
super想知道 如果兔子不死 n月后家里会有多少对兔子
设计一个程序: 输入n, 输出兔子数量
(2 样例输入: 7样例输出:13样例输入: 12样例输出: 144package package01; import java.util.Scanner; public class practise3_3 { public static void main(String[] args) { int n; int m1 = 1, m2 = 1, m3 = 0;; Scanner scanner = new Scanner(System.in); n=scanner.nextInt(); n -= 2; for (int i = n; i >0 ; i--) { m3 = m1 + m2; m1 = m2; m2 = m3; } System.out.println(m3); } }静态方法(或称为类方法),指被 static 修饰的成员方法。
静态方法与实例方法的区别:
静态方法不需要通过它所属的类的任何实例就可以被调用,因此在静态方法中不能使用 this 关键字,也不能直接访问所属类的实例变量和实例方法,但是可以直接访问所属类的静态变量和静态方法。另外,和 this 关键字一样,super 关键字也与类的特定实例相关,所以在静态方法中也不能使用 super 关键字。
在实例方法中可以直接访问所属类的静态变量、静态方法、实例变量和实例方法。
示例:
创建一个带静态变量的类,添加几个静态方法对静态变量的值进行修改,然后在 main( ) 方法中调用静态方法并输出结果。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class StaticMethod {
public static int count = 1; // 定义静态变量count
public int method1() {
// 实例方法method1
count++; // 访问静态变量count并赋值
System.out.println("在静态方法 method1()中的 count="+count); // 打印count
return count;
}
public static int method2() {
// 静态方法method2
count += count; // 访问静态变量count并赋值
System.out.println("在静态方法 method2()中的 count="+count); // 打印count
return count;
}
public static void PrintCount() {
// 静态方法PrintCount
count += 2;
System.out.println("在静态方法 PrintCount()中的 count="+count); // 打印count
}
public static void main(String[] args) {
StaticMethod sft = new StaticMethod();
// 通过实例对象调用实例方法
System.out.println("method1() 方法返回值 intro1="+sft.method1());
// 直接调用静态方法
System.out.println("method2() 方法返回值 intro1="+method2());
// 通过类名调用静态方法,打印 count
StaticMethod.PrintCount();
}
}
运行该程序后的结果如下所示:
1
2
3
4
5
在静态方法 method1()中的 count=2
method1() 方法返回值 intro1=2
在静态方法 method2()中的 count=4
method2() 方法返回值 intro1=4
在静态方法 PrintCount()中的 count=6



