Basic questions for getting started with Java

Table of contents

1. Output each bit of an integer

2. Judgment prime number 

3. Overloading of the maximum value method 

4. Output leap year 

5.Print X graphics 

6. Number of times the number 9 appears

7. Calculate the value of the score 

8. Simulated login

9. Use functions to find the maximum value 

 10. Fibonacci Sequence


The starlight is worthy of the passers-by, come on, you guys! ! !​ 

 

 

1. Output each bit of an integer

topic:

Output each digit of an integer, for example: each digit of 123 is 3, 2, 1

Idea:

This question mainly considers how to obtain each digit of a number:

123 % 10 = 3

123/10=12    12%10=2

12/10=1        1%10= 1

code show as below:

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int num = scan.nextInt();
        while(num != 0){
            int n = num % 10;
            num /= 10;
            System.out.print(n + " ");
        }
    }
}

 

2. Judgment prime number 

topic:

Given a number, determine whether a number is prime 

  • The first method, if a number is a prime number, it can only be divided by 1 and itself.
public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int i;
        for (i = 2;i < n;i++) {
            if(n%i == 0) {
                System.out.println("n不是素数:"+n);
                break;
            }
        }
        if(i >= n) {
            System.out.println(n + "是素数");
        }
}
  • In the second way, any number n can be written in the form n = a*b. Then there must be a number less than or equal to n/2.
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int n = scanner.nextInt();
    int i;
    for (i = 2;i <= n/2;i++) {
        if(n%i == 0) {
            //System.out.println("n不是素数:"+n);
            break;
        }
    }
    if(i > n/2) {
        System.out.println(n + "是素数");
    }
}
  • The third way: any number n can be written in the form n = a*b. Then there must be a number less than or equal to the root n.
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int n = scanner.nextInt();
    int i;
    for (i = 2;i <= Math.sqrt(n);i++) {
        if(n%i == 0) {
            //System.out.println("n不是素数:"+n);
            break;
        }
    }
    if(i > Math.sqrt(n)) {
        System.out.println(n + "是素数");
    }
}

 

(Note: The picture comes from the Internet. If there is any infringement, please contact us to delete it)  

 

3. Overloading of the maximum value method 

topic:

Define multiple methods in the same class: Can you not only find the maximum value of 2 integers, but also the maximum value of 3 decimals?​  

Idea:

To answer this question, we must first understand how overloading is implemented! !

Overloading:1. The method name is the same;2. The parameter list is different (data type, number, order)3. The return value is irrelevant
This question can use the max method in the Java native class Math to find the maximum value. Of course, you can also use If else. Compare.

The use of Math does not require importing related packages

public static int max(int a,int b) {
    return Math.max(a,b);
}

public static double max(double a,double b,double c) {

    double m = Math.max(a,b);
    return Math.max(m,c);
}

It can also be written like this:

public class Main {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int ret1 = max(a , b);
        System.out.println(ret1);
        double c = 2.23;
        double d = 1.32;
        double e = 5.52;
        double ret2 = max(c , d , e);
        System.out.println(ret2);
    }
    
    public static int max(int x, int y){
        return x >= y ? x : y;
    }

    public static double max(double x, double y, double z){
        return x >= y ? x >= z ? x : z : y >= z ? y : z;
    }
}

 

4. Output leap year 

topic:

Output all leap years between 1000 - 2000 

Idea:

First of all, we need to understand what is a leap year? Simply put, it is a year that can be divided evenly by  4 and evenly divided by 100  ; or it can be divided evenly by  400   The year is a leap year!

public static void main(String[] args) {
        for (int year = 1000; year < 2000 ; year++) {
            if(year %4 == 0 && year%100 != 0 || year %400==0) {
                System.out.println(year + " 是闰年!");
            }
        }
}

 

5.Print X graphics 

Title:X-shaped pattern_NiukeTiba_Niuke.com 

Idea:

Assume i represents a row and j represents a column. When i==j or i+j+1 == n, it is an asterisk. The rest are spaces.​ 

 

import java.util.*;


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

 

(Note: The picture comes from the Internet. If there is any infringement, please contact us to delete it) 

 

6. Number of times the number 9 appears

 Topic: 

Write a program to count how many digits 9 appear in all integers from 1 to 100

Idea:

This question mainly examines,How to judge the 9 in the ones place, and how to judge the 9 in the tens place? The other 99 is two 9s. 

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

 

7. Calculate the value of the score 

topic:

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

Idea: 

1 From the above expression it can be analyzed that

  This expression mainly consists of 100 terms, odd terms are positive and even terms are negative

2 Set up a loop from 1 to 100, giving each item in the expression: 1.0/i, Note that 1 cannot be used here, otherwise the results will all be 0< /span>

  Then use the flag tag to control the odd and even items. The odd items are positive and the even items are negative. Then add all the items.

public static void main(String[] args) {

    double sum = 0;
    int flg = 1;
    for (int i = 1; i <= 100; i++) {
        sum += 1.0/i * flg;
        flg = -flg;
    }
    System.out.println(sum);
}

 

8. Simulated login

topic:

Write code to simulate three password entry scenarios. You can enter the password up to three times. If the password is correct, "Login Successful" will be prompted. If the password is wrong, you can re-enter it, up to three times. If the error occurs three times, you will be prompted to exit the program.  

Idea:

Pay attention to this question. How to compare strings to be the same? Usage methodsequals.

public static void main11(String[] args) {
	Scanner scanner = new Scanner(System.in);

	int count = 3;

	while (count != 0) {
		System.out.println("请输入你的密码:");
		String password = scanner.nextLine();

		//if(password == "123") { 这个判断相等是错误的,具体原因后续String章节进行讲解
		
        if(password.equals("123")) {
			System.out.println("登录成功!");
			break;
		}else {
			count--;
			System.out.println("你还有"+count+" 次机会!");
		}
	}
}

 

 (Note: The picture comes from the Internet, if there is any infringement, please contact us to delete it) 

 

9. Use functions to find the maximum value 

topic:

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

Requirements:

In the max3 function, call the max2 function to calculate the maximum value of 3 numbers.

Idea:

This question is relatively simple. The focus is on how to find the maximum value of two numbers. 

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);
	return max > c ? max : c;
}
public static void main(String[] args) {
	System.out.println(max3(2, 5, 1));
}

 

 10. Fibonacci Sequence

topic:

Find the nth term of the Fibonacci sequence. (Iterative implementation) 

Idea:

The Fibonacci sequence is defined as: 1 1 2 3 5 8 13 21 We can see that starting from the 3rd item, they are all equal tothe previous item + the previous item The sum of the previous term. 3 = 1+2, 5 = 2+3, 13 = 5+8.

We can define it firstn1 saves the value of the first item, n2 saves the value of the second item, and n3 saves the value of the third item .

Every time n3 is counted, the values ​​of n1 and n2 are updated simultaneously.

/**

   * 求菲薄那切数列的第n项

   * @param n

   * @return

   */

import java.util.Scanner;

//求斐波那契数列的第n项。(迭代实现)
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        System.out.println(fib(n));
    }

    public static int fib(int n){
        if(n == 1 || n == 2){
            return 1;
        }
        int n1 = 1;  // 1 1 2 3 5 8
        int n2 = 1;
        int n3 = 0;
        for(int i = 3;i <= n; i++){
            n3 = n1 + n2;
            n1 = n2;
            n2 = n3;
        }
        return n3;
    }
}

(Note: The picture comes from the Internet. If there is any infringement, please contact us to delete it)  

Hope it helps everyone, thank you for watching! ! !

 

Guess you like

Origin blog.csdn.net/A1546553960/article/details/134409190