I'm Chen PI. I'm an ITer of Internet Coding. I search "Chen Pi's JavaLib" on wechat. I can read the latest article at the first time and reply to [data], so I can get my carefully sorted technical data, e-books, interview data of front-line large factories and excellent resume template.
introduction
During college, Java language is generally used as a course for computer majors, and many students will choose Java as the main language for learning programming. After learning and mastering the basic knowledge, writing code through a large number of programming exercises is one of the important means to consolidate the basic knowledge and exercise programming thinking. Here are 50 examples of Java language practice, title + problem solving idea + solution.
1 tower of Hanoi
Title: suppose there are three needles A, B and C on A board. There are 64 discs of different sizes sleeved on needle A, which are arranged in the order of large ones in the bottom and small ones in the top. To move these 64 discs from needle A to needle C, only one disc can be moved at A time, and needle B can be used in the moving process. But at any time, the disc on any needle must keep the big disc at the bottom and the small disc at the top. Input the number of discs to be moved from the keyboard and give the moving process.
Analysis: the whole moving process of the disc is realized by recursion; When only one disc is moved, move the disc directly from needle A to needle C. If the moving disc is n (n > 1), it is divided into several steps: move (n-1) discs from needle A to needle B (with the help of needle C); The last disc on needle A moves to needle C; (n-1) discs on needle B move to needle C (with the aid of needle A). Each time you do it, the number of moving discs is one less, decreasing step by step. Finally, when n is 1, the whole moving process is completed.
package com.nobody; /** * @Description * @Author Mr.nobody * @Date 2021/5/31 * @Version 1.0 */ public class Demo { public static void main(String[] args) { // Move the 3 plates from A to C hanoi(3, 'A', 'B', 'C'); } /** * Hanoi Tower transfer process * * @param n Number of plates * @param from Starting point column * @param inter Transfer column * @param to Terminal column */ public static void hanoi(int n, char from, char inter, char to) { // When there is only one plate left, move directly from from to to if (n == 1) { System.out.println("Plate 1 from " + from + " Move to " + to); } else { // Move the top n-1 plates from the starting point to the transfer column with the help of the end point hanoi(n - 1, from, to, inter); // Move the current largest plate directly from the starting point to the ending point System.out.println("plate" + n + "from " + from + " Move to " + to); // Then move the just n-1 plates from the transfer point to the end with the help of the starting point hanoi(n - 1, inter, from, to); } } }
The output of the demo code is as follows:
Plate 1 from A Move to C Plate 2 from A Move to B Plate 1 from C Move to B Plate 3 from A Move to C Plate 1 from B Move to A Plate 2 from B Move to C Plate 1 from A Move to C
2 Fibonacci sequence
Title: the first term of Fibonacci sequence is 0, the second term is 1, and the value of each term is the sum of the first two terms starting from the third term. For example, item 3 is the sum of items 1 and 2, that is, 0 + 1 = 1, and item 4 is the sum of items 2 and 3, that is, 1 + 1 = 2. It is such a sequence of numbers 0, 1, 1, 2, 3, 5, 8, 13, 21
Analysis: because the first two items are special, they are treated separately. Starting from item 3, the value of the next item can be calculated by the sum of the first two items. There are two solutions. One solution is to keep the values of the first two items through two variables, and then sum them. Another solution is to recursively calculate the values of the first two items from the current item until the values of item 1 and item 2.
package com.nobody; /** * @Description Recursive solution * @Author Mr.nobody * @Date 2021/5/31 * @Version 1.0 */ public class Demo { public static void main(String[] args) { // Top 20 output int num = 20; for (int i = 1; i <= num; i++) { System.out.println("Fibonacci sequence No" + i + "Item is" + fibonacci(i)); } } public static long fibonacci(long number) { // Items 1 and 2 are specially processed, that is, 0 and 1 are returned if (number == 1 || number == 2) { return number - 1; } else { // Excluding items 1 and 2, they are the sum of the first two items return fibonacci(number - 2) + fibonacci(number - 1); } } }
package com.nobody; /** * @Description Non recursive solution * @Author Mr.nobody * @Date 2021/5/31 * @Version 1.0 */ public class Demo { public static void main(String[] args) { // Top 20 output int num = 20; // Save the values of the first two items int x = 0, y = 1; // The value of the current item int curData; for (int i = 1; i <= num; i++) { // Items 1 and 2 are specially processed, that is, 0 and 1 are returned if (i == 1 || i == 2) { System.out.println("Fibonacci sequence No" + i + "Item is" + (i - 1)); } else { // Excluding items 1 and 2, they are the sum of the first two items curData = x + y; System.out.println("Fibonacci sequence No" + i + "Item is" + curData); x = y; y = curData; } } } }
The output of the demo code is as follows:
The first item of Fibonacci sequence is 0 The second item of Fibonacci sequence is 1 The third item of Fibonacci sequence is 1 The fourth item of Fibonacci sequence is 2 The fifth item of Fibonacci sequence is 3 The sixth item of Fibonacci sequence is 5 The seventh item of Fibonacci sequence is 8 The eighth item of Fibonacci sequence is 13 The ninth item of Fibonacci sequence is 21 The 10th item of Fibonacci sequence is 34 The 11th item of Fibonacci sequence is 55 The 12th item of Fibonacci sequence is 89 The 13th item of Fibonacci series is 144 The 14th item of Fibonacci sequence is 233 The 15th item of Fibonacci series is 377 The 16th item of Fibonacci sequence is 610 The 17th item of Fibonacci series is 987 The 18th item of Fibonacci sequence is 1597 The 19th item of Fibonacci sequence is 2584 The 20th item of Fibonacci series is 4181
3 99 multiplication table
Title: output 99 multiplication table.
Analysis: use a two-layer for loop to traverse the output 99 multiplication table.
package com.nobody; /** * @Description multiplication table * @Author Mr.nobody * @Date 2021/5/31 * @Version 1.0 */ public class Demo { public static void main(String[] args) { for (int i = 1; i <= 9; i++) { for (int j = 1; j <= i; j++) { System.out.print(j + "×" + i + "=" + i * j + "\t"); } System.out.println(); } } }
The output of the demo code is as follows:
1×1=1 1×2=2 2×2=4 1×3=3 2×3=6 3×3=9 1×4=4 2×4=8 3×4=12 4×4=16 1×5=5 2×5=10 3×5=15 4×5=20 5×5=25 1×6=6 2×6=12 3×6=18 4×6=24 5×6=30 6×6=36 1×7=7 2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49 1×8=8 2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64 1×9=9 2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81
4 string replacement
Title: replace a substring of a string with another string. For example, if the Java substring of the JavaLib of tangerine peel is replaced with C, it will eventually become the CLib of tangerine peel.
Analysis: there are many practical classes in the Java class library, and many general methods are defined. You can use the replace method of String class.
package com.nobody; /** * @Description * @Author Mr.nobody * @Date 2021/5/31 * @Version 1.0 */ public class Demo { public static void main(String[] args) { String str = "I am tangerine, my official account. JavaLib]"; System.out.println("replace all`dried tangerine peel`by`son of a bitch`String after:" + str.replace("dried tangerine peel", "son of a bitch")); System.out.println("replace all`dried tangerine peel`by`son of a bitch`String after:" + str.replaceAll("dried tangerine peel", "son of a bitch")); System.out.println("Replace only one`dried tangerine peel`by`son of a bitch`String after:" + str.replaceFirst("dried tangerine peel", "son of a bitch")); } }
The output of the demo code is as follows:
replace all`dried tangerine peel`by`son of a bitch`After that string: I am a dog egg, my official account. JavaLib] replace all`dried tangerine peel`by`son of a bitch`After that string: I am a dog egg, my official account. JavaLib] Replace only one`dried tangerine peel`by`son of a bitch`After that string: I am a dog egg, my official account. JavaLib]
5 string inversion
Title: reverse the string, for example, abcde to edcba.
Directly call the buffer method of the string reverse class.
package com.nobody; /** * @Description * @Author Mr.nobody * @Date 2021/5/31 * @Version 1.0 */ public class Demo { public static void main(String[] args) { String str = "abcde"; String reverse = new StringBuffer(str).reverse().toString(); System.out.println(str + "After reversal:" + reverse); } }
The output of the demo code is as follows:
abcde After reversal:edcba
6 print inverted triangles
Title: print inverted triangles and use the * sign to print.
Analysis: for inverted triangles, we use the method of printing from one line to the next. Note that when printing each line, we need to calculate how many spaces need to be printed in front of each line.
package com.nobody; /** * @Description Print inverted triangles * @Author Mr.nobody * @Date 2021/5/31 * @Version 1.0 */ public class Demo { public static void main(String[] args) { // Print 6 lines of inverted triangles for (int i = 1; i <= 6; i++) { // Print the space before each line, and the next line will always have one more space than the previous line for (int j = 0; j <= i; j++) { System.out.print(" "); } // Print* for (int k = 1; k <= 11 - 2 * (i - 1); k++) { System.out.print("*"); } System.out.println(); } } }
The output of the demo code is as follows:
*********** ********* ******* ***** *** *
7 resolve URL
Title: URL address is composed of several parts, such as protocol, IP, port, file name, etc. Please extract it from the URL.
Analysis: through the URL class, many methods are defined to extract the corresponding information in the URL.
package com.nobody; import java.net.URL; /** * @Description Resolve URL * @Date 2021/5/31 * @Version 1.0 */ public class Demo { public static void main(String[] args) throws Exception { URL url = new URL("http://www.nobody.com/html/index.html"); System.out.println("URL: " + url.toString()); System.out.println("agreement:" + url.getProtocol()); System.out.println("host:" + url.getHost()); System.out.println("Port number:" + url.getPort()); System.out.println("File name:" + url.getFile()); System.out.println("route:" + url.getPath()); System.out.println("Default port number:" + url.getDefaultPort()); } }
The output of the demo code is as follows:
URL: http://www.nobody.com/html/index.html agreement: http host: www.nobody.com Port number:-1 File name:/html/index.html route:/html/index.html Default port number: 80
8 daffodils
Title: narcissus number refers to a three digit number, and the sum of each digit cube is equal to the number itself. For example: 153 is the number of daffodils, 153 = 1 ^ 3 + 5 ^ 3 + 3 ^ 3
Analysis: traverse the number between 100-999 and calculate whether the cube of each number is equal to itself.
package com.nobody; /** * @Description Narcissistic number * @Date 2021/5/31 * @Version 1.0 */ public class Demo { public static void main(String[] args) { int x, y, z; for (int i = 100; i <= 999; i++) { x = i % 10; y = i / 10 % 10; z = i / 100 % 10; if (i == (x * x * x + y * y * y + z * z * z)) { System.out.println(i); } } } }
The output of the demo code is as follows:
153 370 371 407
9 Yanghui triangle
Title: the number of two waist sides of Yang Hui triangle is 1, and the number of other positions is the sum of the two numbers on the top.
package com.nobody; /** * @Description Yanghui triangle * @Date 2021/5/31 * @Version 1.0 */ public class Demo { public static void main(String[] args) { // Number of lines to print int n = 10; int i, j, k; int[][] a = new int[n + 1][n + 1]; System.out.println(n + "The Yanghui triangle is as follows:"); for (i = 1; i <= n; i++) { // The number on both sides makes it 1 a[i][1] = a[i][i] = 1; } for (i = 3; i <= n; i++) { for (j = 2; j <= i - 1; j++) { // Except for the numbers on both sides, they are equal to the sum of the top two numbers a[i][j] = a[i - 1][j - 1] + a[i - 1][j]; } } for (i = 1; i <= n; i++) { for (k = 1; k <= n - i; k++) { // Make the display beautiful and mark the appropriate space before the output number System.out.print(" "); } for (j = 1; j <= i; j++) { System.out.printf("%6d", a[i][j]); } // Wrap a line after a line of digital output System.out.println(); } } }
The output of the demo code is as follows:
10 The Yanghui triangle is as follows: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1
10 decomposition quality factor
Topic: decompose a positive integer into prime factors. For example: enter 80 and print out 80 = 2 * 2 * 2 * 2 * 5.
Analysis: because the minimum prime factor is 2, the incremental traversal starts from 2, and the maximum is no more than half of the integer. If a prime factor is not found, remove the prime factor and continue traversal.
package com.nobody; import java.util.Scanner; /** * @Description Decomposition quality factor * @Date 2021/5/31 * @Version 1.0 */ public class Demo { public static void main(String[] args) { System.out.print("Please enter an integer that requires a factorization factor:"); Scanner scanner = new Scanner(System.in); int num = scanner.nextInt(); // Decomposition quality factor System.out.print(num + "Decomposition quality factor:"); int tmp = num / 2; for (int i = 2; i <= tmp; i++) { if (num % i == 0) { num = num / i; System.out.print(i + " "); i = 1; } } } }
The output of the demo code is as follows:
Please enter an integer that requires a factorization factor: 80 80 Decomposition quality factor: 2.5
11 free fall of small ball
Title: a ball falls freely from a height of 100 meters. After each landing, it jumps back to half of the original height and falls again. How many meters does it pass on the 10th landing? How high is the 10th rebound?
Analysis: the first time I fell from a height of 100 meters, and this path needs to be handled separately, that is, when I fell to the ground for the first time, I passed 100 meters, and the height is 0 meters. Then, according to each time the small ball bounces up and back, the distance passed back and forth each time is twice the height of the bounce.
package com.nobody; /** * @Description The ball falls freely * @Date 2021/5/31 * @Version 1.0 */ public class Demo { public static void main(String[] args) { float h = 100, s = 100; // First rebound height h = h / 2; for (int i = 2; i <= 10; i++) { s = s + 2 * h; h = h / 2; } System.out.printf("On the 10th landing, a total of%f Meters, the 10th rebound high%f rice", s, h); } }
The output of the demo code is as follows:
On the 10th landing, 299.609375 Meters, the 10th rebound is 0.097656 rice
12 judge leap year
Title: a leap year can be divided by 4, not 100, or 400. Then this year is a leap year.
Analysis: judge whether the year can be divided by 4, not 100, or 400. If one of the two conditions is true, then this year is a leap year.
package com.nobody; import java.util.Scanner; /** * @Description Judge leap year * @Date 2021/5/31 * @Version 1.0 */ public class Demo { public static void main(String[] args) { System.out.print("Please enter the year:"); Scanner sc = new Scanner(System.in); int year = sc.nextInt(); // Judge whether the year can be divided by 4 but not 100 boolean isLeapYear = (year % 4 == 0) && (year % 100 != 0); // Determine whether the year can be divided by 400 boolean isLeapYear1 = year % 400 == 0; // One of the two conditions is leap year if (isLeapYear || isLeapYear1) { System.out.println(year + "It's a leap year!"); } else { System.out.println(year + "Not a leap year!"); } } }
The output of the demo code is as follows:
Please enter year: 2021 2021 Not a leap year! Please enter year: 2020 2020 It's a leap year!
13 factorial
Title: the factorial of a positive integer is the product of all positive integers less than or equal to the number, and the factorial of 0 is 1. The factorial of natural number n is written as n!, n!= one × two × three ×…× n.
Analysis: calculating the factorial of a number n is actually equal to the factorial of n-1 and then multiplied by N, so it can be realized by recursion.
package com.nobody; import java.util.Scanner; /** * @Description Factorial * @Date 2021/5/31 * @Version 1.0 */ public class Demo { public static void main(String[] args) { System.out.print("Please enter an integer:"); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for (int i = 0; i <= n; i++) { System.out.printf("%d! = %d\n", i, factorial(i)); } } public static long factorial(long n) { if (n <= 1) { return 1; } else { return n * factorial(n - 1); } } }
The output of the demo code is as follows:
Please enter an integer: 10 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800
Keep updating, focus on collections, keep learning Java language exercises
Recommend to you the learning and growth knowledge map of Java engineers exclusively produced by CSDN, which covers comprehensive knowledge points. You can start with it if you are interested. It is recommended, especially for college students. If you can learn and master these knowledge points, it is not a dream to cut off the Offer of BAT factory! 😉