JavaSE02, method, recursive iteration

Keywords: Java Programming JavaSE recursion

1, Input and output

The first way:

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) throws IOException {
        System.out.print("Enter a Char:");
        char i = (char)System.in.read(); // Alt + ENTER
        System.out.println("your char is :"+i);
    }
}

The second way:

1. If an integer and a string are read at the same time, read the string first
2.next – > spaces cannot be read
– > nextline – > read including spaces

import java.util.Scanner;

public class TestDemo {
	public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); // Read from keyboard
        int n = scanner.nextInt();
        System.out.println(n);

        /* double d = scanner.nextDouble();
        System.out.println(d); */

        // Put it in front of n before you can enter
        String str1 = scanner.nextLine();
        System.out.println(str1);

        // next cannot read spaces
        String str2 = scanner.nextLine();

        // close
        scanner.close();
    }
}

Cycle reading n numbers

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()) { // End: Ctrl+d
            int n = scanner.nextInt();
            System.out.println(n);
        }
    }
}

2, Method

Method: the function -- > function of C can be reused
public static return value method name (formal parameter list){
Function body; / / method body
}

1. Find the sum of 1-10**

public class TestDemo {
	 /**
     * Find the sum of 1-n
     * Function name: small hump
     * @param n Number entered
     * @return Sum of
     */
    public static int sumAdd(int n) {
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        return sum;
    }
    
    public static void main(String[] args) {
		int ret = sumAdd(10); // Method call
        System.out.println(ret);
    }
}

2. Attention problem

public class TestDemo {
	 
    public static int sumAdd(int n) {
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        return sum;
    }
   
    >1. java There is no concept of "function declaration"
	>2. The method must be defined in the class, and the code can be written above or below the calling position
	>3. Function to open up memory--Stack frame
	>4. When each function is called, it will open up the stack frame, which belongs to the memory of this function
   
    public static void main(String[] args) {
		// System.out.println(func()); // err

        System.out.println(sumAdd(10)*2); // The return value of the function supports chained calls
    }

    public static void func() {

    }
}

3. Calculate 1! + 2! + 3! + 4! + 5!

public class TestDemo {
    public static int fac(int n) {
        int ret = 1;
        for (int i = 1; i <= n; i++) {
            ret *= i;
        }
        return ret;
    }
    
    /**
     * Find the sum of factorials of n
     * Reading ability has improved
     * @param n
     * @return
     */
    public static int facSum(int n) {
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += fac(i);
        }
        return sum;
    }
    
    public static void main(String[] args) {
		System.out.println(facSum(5));
    }
}

4. Formal and argument

public class TestDemo {
	public static void swap(int a, int b) {
        // java, can't get the address on the stack
        // If you want to exchange, you can only put a and b on the heap
        int tmp = a;
        a = b;
        b = tmp;
    }
    
    public static void main(String[] args) {
		int a = 10;
        int b = 20;
        System.out.println("Before exchange:"+a+" "+b);
        swap(a, b);
        System.out.println("After exchange:"+a+" "+b);
    }
}

5. overload of method

Overloaded rules:
It can not be a class (or inheritance relationship)
1. Same method name
2. The parameter list of the method is different (number or parameter type)
3. The return value type of the method does not affect overloading

Example: add finds the sum of two integers, two decimals and three integers

public class TestDemo {
	public static int add(int a, int b) {
        return a + b;
    }
    public static double add(double a, double b) {
        return a + b;
    }
    public static int add(int a, int b, int c) {
        return a + b + c;
    }
}

6. Simulate user input password

import java.io.IOException;
import java.util.Random;
import java.util.Scanner;

public class TestDemo {
    public static void login() {
        Scanner scanner = new Scanner(System.in);
        int count = 3;
        while(count != 0) {
            System.out.println("Please enter your password:");
            String password = scanner.nextLine();
            if(password.equals("12345")) {
                System.out.println("Login succeeded!");
                break;
            } else {
                count--;
                System.out.println("Wrong password, you still have "+count+"A chance!");
            }
        }
    }

    public static void main(String[] args) {
        // Simulate user input password
        login();
    }
}

7. Recursion

Recursion: a method calls its own procedure

  1. There is a condition that tends to terminate
  2. Call yourself

7.1 factorial of n

public class TestDemo {

    public static int fac(int n) {
        if(n == 1) {
            return 1;
        }
        int tmp = n * fac(n-1);
        return tmp;
    }

	public static void main(String[] args) {
        System.out.println(fac(5));
    }
}

7.2 sum of n

sumAdd(10) --> 1+2+3+...+10

public class TestDemo {

    public static int sumAdd(int n) {
        if(n == 1) {
            return 1;
        } else {
            return n + sumAdd(n-1);
        }
    }

	public static void main(String[] args) {
        int sum = sumAdd(3);
        System.out.println(sum);
    }
}

7.3. Print each bit in sequence

public class TestDemo {
	public static void printNum(int n) {
        if(n < 10) {
            System.out.print(n%10+" ");
        }else {
            printNum(n/10);
            System.out.print(n%10+" ");
        }
    }

	public static void main(String[] args) {
        printNum(123);
    }
}

7.4. Return the sum of each person 1234 – > 1 + 2 + 3 + 4

public class TestDemo {
	public static int sumEveryNum(int n) {
        if(n < 10) {
            return n;
        }else {
            return n % 10 + sumEveryNum(n/10);
        }
    }

	public static void main(String[] args) {
        System.out.println(sumEveryNum(1725));
    }
}

7.5 Fibonacci number

public class TestDemo {
	public static int fib(int n) {
        // recursion
        if(n == 1 || n == 2) {
            return 1;
        }else {
            return fib(n-1) + fib(n-2);
        }
    }

    public static int fib2(int n) {
        // Loop / iteration
        if(n == 1 || n == 2) {
            return 1;
        }
        int f1 = 1;
        int f2 = 1;
        int f3 = 0;
        for (int i = 3; i <= n; i++) {
            f3 = f1 + f2;
            f1 = f2;
            f2 = f3;
        }
        return f3;
    }

	public static void main(String[] args) {
        System.out.println(fib(10));

        System.out.println(fib2(50));
    }
}

7.6 frog jumping steps

public class TestDemo {
	public static int frogJump(int n) {
        // recursion
        if(n == 1 || n == 2) {
            return n;
        }else {
            return frogJump(n-1) + frogJump(n-2);
        }
    }

    public static int frogJump2(int n) {
        // iteration
        if(n == 1 || n == 2) {
            return n;
        }
        int f1 = 1;
        int f2 = 2;
        int f3 = 0;
        for (int i = 3; i <= n; i++) {
            f3 = f1 + f2;
            f1 = f2;
            f2 = f3;
        }
        return f3;
    }
    
	public static void main(String[] args) {
        System.out.println(frogJump(1));
        System.out.println(frogJump(2));
        System.out.println(frogJump(3));
        System.out.println(frogJump(4));

        System.out.println(frogJump2(1));
        System.out.println(frogJump2(2));
        System.out.println(frogJump2(3));
        System.out.println(frogJump2(4));
    }
}

3, Programming problem

1. Figure guessing game

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
        Random random = new Random();
        int rand = random.nextInt(100);
        Scanner scanner = new Scanner(System.in);
        while(true) {
            System.out.print("Please enter the number you want to guess:");
            int n = scanner.nextInt();
            if (n < rand) {
                System.out.println("Guess it's small");
            } else if (n == rand) {
                System.out.println("You guessed right");
                break;
            } else {
                System.out.println("Guess big");
            }
        }
}

2. Judgement prime

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
		// Given a number, determine whether a number is a prime number
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt();
        int i = 0;
        for (i = 2; i < num; i++) {
            if(num % i == 0) {
                System.out.println(num+"num Not prime!");
                break;
            }
        }
        if(i == num) {
            System.out.println("num It's a prime");
        }
    }
}

Optimization 1:

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
		// N -- > A * B example 16 1 * 16 2 * 8 4 * 4, there must be a number less than or equal to 16 / 2 -- 8
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt();
        int i = 0;
        for (i = 2; i <= num / 2; i++) { //
            if(num % i == 0) {
                System.out.println(num+"num Not prime!");
                break;
            }
        }
        if(i > num / 2) { //
            System.out.println("num It's a prime");
        }
    }
}

Optimization 2:

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
		// N -- > A * B example 16 1 * 16 2 * 8 4 * 4, where there must be a number less than or equal to the root n --4
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt();
        int i = 0;
        for (i = 2; i <= Math.sqrt(num); i++) { //
            if(num % i == 0) {
                System.out.println(num+"num Not prime!");
                break;
            }
        }
        if(i > Math.sqrt(num)) { //
            System.out.println("num It's a prime");
        }
    }
}

3. Output 9 * 9 multiplication formula table

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
		for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(i+"*"+j+"="+i*j+" ");
            }
            System.out.println();
        }
    }
}

4. Find the greatest common divisor of two positive integers

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
  	    // Rolling phase division
		int a = 24;
        int b = 18;
        int c = a % b; // 24 % 18 = 6
        while(c != 0) {
            a = b;
            b = c;
            c = a % b;
        }
        System.out.println("The greatest common divisor is"+b);
    }
}

5. Calculate the value of 1 / 1-1 / 2 + 1 / 3-1 / 4 + 1 / 5... + 1 / 99 - 1 / 100

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
		double sum = 0.0;
        int flag = 1;
        for (int i = 1; i <= 100; i++) {
            sum += (1.0 / i) * flag;
            flag = -flag;
        }
        System.out.println(sum); // 0.688172179310195
    }
}

6. How many digits 9 appear in all integers from 1 to 100

import java.util.Scanner;

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
		int count = 0;
        for(int i = 1; i <= 100; i++) {
            if(i % 10 == 9) {
                count++;
            }
            if(i / 10 == 9) {
                count++;
            }
        }
        System.out.println(count);
    }
}

7. Daffodils number

public class TestDemo {
    public static void findNum(int n) {
        for (int i = 1; i <= n; i++) {
            int count = 0; // Calculate the number of digits of a number
            int tmp = i;
            while(tmp != 0) {
                count++;
                tmp /= 10;
            }
            tmp = i;
            int sum = 0;
            while(tmp != 0) {
                sum += Math.pow(tmp %  10, count);
                tmp /= 10;
            }
            if(sum == i) {
                System.out.println(i);
            }
        }
    }
	
	public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt(); // 999999
        findNum(n);
	}
}

8. How many bits are there 1

public class TestDemo {
    public static int numOfOne(int n) {
        // How many bits are there 1
        int count = 0;
        while (n != 0) {
            if ((n & 1) == 1) {
                count++;
            }
            n = n >>> 1; // unsigned right shift 
        }
        return count;
    }
	
    public static int numOfOne2(int n) {
        int count = 0;
        while (n != 0) {
            count++;
            n = n & (n - 1);
        }
        return count;
    }
    
	public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        
        System.out.println(numOfOne(n));
	}
}

9. Obtain odd and even digits and output them respectively

public class TestDemo {

    public static void printBinary(int n) {
        for (int i = 30; i >= 0; i-=2) {
            System.out.print(((n >> i) & 1)+" ");
        }
        System.out.println();
        for (int i = 31; i >= 1; i-=2) {
            System.out.print(((n >> i) & 1)+" ");
        }
    }

	public static void main(String[] args) {
        printBinary(15);
    }
}

10. Reverse order printing

public class TestDemo {

    public static void printNum(int n) {
        while(n != 0) {
            System.out.print(n%10+" ");
            n /= 10;
        }
    }

	public static void main(String[] args) {
        printNum(123);
    }
}

11. There is a set of data. Only one number appears once and the others twice. Please find out this number

public class TestDemo {

	public static void main(String[] args) {
        int[] array = {1, 2, 3, 2, 1};
        // int sum = 0;
        int sum = array[0];
        for (int i = 1; i < array.length; i++) {
            sum = sum ^ array[i];
        }
        System.out.println(sum);
    }
}

12, adjust the array order to make odd numbers even before even numbers. After adjusting, do not care about the order of size.

public class TestDemo {

	public static void main(String[] args) {
        int[] array = {1,2,3,4,5,6,7,8,9,10};
        int left = 0;
        int right = array.length-1;

        while(left < right) {
            while(left < right && array[left] % 2 == 0) {
                left++;
            }
            while(left < right && array[right] % 2 != 0) {
                right--;
            }
            int tmp = array[left];
            array[left] = array[right];
            array[right] = tmp;
        }

        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]+" ");
        }
    }
}

13. X-shaped pattern

describe
KiKi learned the cycle, and teacher BoBo gave him a series of practice of printing patterns. The task is to print X-shaped patterns composed of "*".
Enter Description:
Multiple sets of inputs, an integer (2 ~ 20), represents the number of output lines, and also represents the length of backslash and forward slash constituting "X".
Output Description:
For each line of input, an X-shaped pattern composed of "*" is output.

/*import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNext()) {
            int n = scanner.nextInt();
            int i = 0;
            for(i = 0; i< n; i++) {
                int j = 0;
                for(j=0; j<n; j++) {
                    if(j == i || j + i == n - 1) {
                        System.out.print("*");
                    }
                    else {
                        System.out.print(" ");
                    }
                }
                System.out.println();
            }
        }
    }
}*/

import java.util.*;

public class Main {
    
    public static void func(int n) {
        for(int i = 0; i< n; i++) {
            for(int j=0; j<n; j++) {
                if(j == i || j + i == n - 1) {
                    System.out.print("*");
                 }else {
                    System.out.print(" ");
                 }
            }
            System.out.println();
         }
    }
    
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while(scan.hasNextInt()) {
            int n = scan.nextInt();
            func(n);
        }
    }
}

14. Find the maximum value

Create a method to find the maximum value max2 of two numbers, and then write a function max3 to find the maximum value of three numbers.

Requirements: in the max3 function, call the max2 function to achieve the maximum calculation of the 3 numbers.

import java.util.Random;
import java.util.Scanner;

public class TestDemo {

    /**
     * @param a
     * @param b
     * @return
     */public static int max2(int a, int b) {
        return a > b ? a : b;
    }
    public static int max3(int a, int b, int c) {
        int max = max2(a, b);
        max = max2(max, c);
        return max;
    }

    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 20;
        int num3 = 30;
        int maxAB = max2(num1, num2);
        System.out.println("max->num1 num2: "+maxAB);

        int maxABC = max3(num1, num2, num3);
        System.out.println("max->num1 num2 num3: "+maxABC);
    }
}

15. Overload of maximum method

Define multiple methods in the same class: it is required to find not only the maximum value of two integers, but also the maximum value of two decimals, and the size relationship between two decimals and an integer

public static TestDemo {
        
    public static int maxN(int x, int y) {
        return x > y ? x : y;
    }

    public static double maxN(double x, double y) {
        return x > y ? x : y;
    }

    public static void maxN(int x, double y, double z) {
        double tmp =  x > y ? x : y; // x y --> maxdouble max = tmp > z ? tmp : z;
        double tmp2 = x < y ? x : y;
        double min = tmp2 < z ? tmp2 : z;
        double mid = (x*1.0 + y + z) - max - min;
        System.out.println(max+">"+mid+">"+min);

    }

    public static void main(String[] args) {
        System.out.println(maxN(10, 20));
        System.out.println(maxN(2.7, 5.8));
        maxN(3, 2.1, 3.7);
    }

}

Posted by achilles on Sat, 23 Oct 2021 20:42:57 -0700