Article directory
I. Introduction
Algorithm homework, originally written in C language, but VScode has been convulsed. Recently, the school is studying Java, so you might as well write in a different grammar. My
current feeling: the grammar of JavaSE is actually the same as that of C.
Second, the problem of rabbit reproduction
1. Question
Typical Fibonacci sequence
1 、 1 、2 、 3 、 5 、8 、 13 、 21 、34…
2. Solution
① Method 1
Iteration relation y[ i ] = y[ i-1 ] + y[ i-2 ]
public class Rabit_1 {
public static void main(String[] args) {
int[] arr=new int[3];
int i,j;
System.out.println("请输入当前的月数");
Scanner scanner=new Scanner(System.in);
j=scanner.nextInt();
arr[0]=arr[1]=1; //1,2月兔子个数为1
System.out.println("arr[1] = "+arr[0]);
System.out.println("arr[2] = "+arr[1]);
for(i=2;i<j;i++){
arr[2]=arr[1]+arr[0];
System.out.println("arr["+(i+1)+"] = "+arr[2]);
arr[0]=arr[1];
arr[1]=arr[2];
}
}
}
② Method 2
Iteration relation
a = b+c; b = a+c; c = a+b;
public class Rabit2 {
public static void main(String[] args) {
int a=1,b=1,c,i;
for(i=1;i<=4;i++){
c=a+b;
a=b+c;
b=c+a; //输出的结果不完美
System.out.print(a+" "+b+" "+c+" ");
}
}
}
③ Method 3
Iteration relation
a = a+b; b = a+b;
public class Rabit3 {
public static void main(String[] args) {
int i,a=1,b=1;
System.out.print(a+" "+b+" ");
for(i=1;i<=5;i++){
a=a+b;
b=a+b;
System.out.print(a+" "+b+" ");
}
}
}
3. Find the greatest common divisor
1. Method 1
Exhaustive method
public class Gongyueshu_1 {
public static void main(String[] args){
int a,b,t;
System.out.println("输入两个整数");
Scanner scanner=new Scanner(System.in);
a=scanner.nextInt();
b=scanner.nextInt();
t=a<b? a: b; //取ab中较小的数
while(!(a%t==0&&b%t==0)){
t--;
}
System.out.println(a+"和"+b+"的最大公约数为 "+t);
}
}
2. Method 2
Roll and divide
public class Gongyueshu_2 {
public static void main(String[] args) {
int a,b,r,a1,b1;
System.out.println("请输入两个整数");
Scanner scanner=new Scanner(System.in);
a=scanner.nextInt();
b=scanner.nextInt();
a1=a;
b1=b;
while(b!=0){
r=a%b;
a=b;
b=r;
}
System.out.println(a1+"和"+b1+"的最大公约数是 "+a);
}
}
3. Method three
Subtraction
public class Gongyueshu3 {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int a,b;
System.out.println("请输入两个整数");
a=scanner.nextInt();
b=scanner.nextInt();
if(a==b) {
System.out.println("最大公约数是:" + a);
}else{
while(a!=b){
if(a>b)
a=a-b;
else
b=b-a;
}
System.out.println("最大公约数是:" + a);
}
}
}
Four, this () usage
1. Introduction
When the teacher mentioned the keyword this in class before, the this. variable name was clearly explained
① Directly refer to
this to point to the current object itself
② Avoid duplication
Formal participation member variables are repeated, use this to distinguish
③ this()
refers to the constructor
this (parameter): Call another form of constructor in this class (should be the first statement in the constructor).
2. Code
① Person class
② Main function Main