1、打印出从1到100的偶数(2的倍数)
2、判断101-200之间有多少个素数,并输出所有素数(在大于1的自然数中,除了1和它本身以外不再有其他因数的数)
提示:判断素数的方法:用这个数分别去除2到这个数平方根,如果能被整除, 则表明此数不是素数,反之是素数。
3、打印出以下效果(说明:n!=n*(n-1)*(n-2)* ... 1)
1!=1;
2!=2;
3!=6;
4!=24;
5!=120;
4、有1、2、3、4四个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?
5、将一个无序的数组从小到大排序
6、有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
定义方法(递归):
面向对象:
import java.util.ArrayList;
import java.util.Scanner;
class Rabbit {
private int age;
public Rabbit(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//生小兔子
public Rabbit bornRabbits(){
if (this.age > 2){
Rabbit baby = new Rabbit(0);
return baby;
}else {
return null;
}
}
public static void main(String[] args) {
ArrayList<Rabbit> rabbits = new ArrayList<>();
Rabbit n = new Rabbit(1);
rabbits.add(n);
Scanner scanner = new Scanner(System.in);
System.out.print("请输入月份:");
int month = scanner.nextInt();
for (int i = 1; i < month; i++) {
for (int j = 0; j < rabbits.size(); j++) {
Rabbit current = rabbits.get(j);
current.setAge((current.age + 1));
Rabbit baby = current.bornRabbits();
if(baby != null){
rabbits.add(baby);
}
}
}
System.out.println(month + "月份共有" + (rabbits.size()) + "只兔子");
}
}
预习思考题:假如兔子长大到10个月就不再生小兔子了呢?假如兔子长到15个月就老死了呢?
import java.util.ArrayList;
import java.util.Scanner;
class Rabbit {
private int age;
public Rabbit(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//生小兔子
public Rabbit bornRabbits(){
if (this.age > 2 && this.age <= 10){
Rabbit baby = new Rabbit(0);
return baby;
}else {
return null;
}
}
public static void main(String[] args) {
ArrayList<Rabbit> rabbits = new ArrayList<>();
Rabbit n = new Rabbit(1);
rabbits.add(n);
Scanner scanner = new Scanner(System.in);
System.out.print("请输入月份:");
int month = scanner.nextInt();
for (int i = 1; i < month; i++) {
for (int j = 0; j < rabbits.size(); j++) {
Rabbit current = rabbits.get(j);
current.setAge((current.age + 1));
if (current.age == 15){
rabbits.remove(current);
}
Rabbit baby = current.bornRabbits();
if(baby != null){
rabbits.add(baby);
}
}
}
System.out.println(month + "月份共有" + (rabbits.size()) + "只兔子");
}
}