50 classic Java programming exercises to apply mathematical thinking to programming.
1. Index calculation
There is a pair of rabbits. They give birth to a pair of rabbits every month from the third month after birth. The little rabbit grows to another pair of rabbits every month after the third month. If the rabbits don't die, what are the logarithm of rabbits every month?
Program analysis: the law of rabbits is sequence 1,1,2,3,5,8,13,21
public class Prog1{ public static void main(String[] args){ int n = 10; System.out.println("The first"+n+"The total number of rabbits in months is"+fun(n)); } private static int fun(int n){ if(n==1 || n==2) return 1; else return fun(n-1)+fun(n-2); } }
2. Specify the prime number contained in the range
Judge how many primes there are between 101-200, and output all primes.
Program analysis: method of judging prime numbers: use a number to remove 2 to sqrt (this number) respectively. If it can be divided, it indicates that this number is not a prime number, on the contrary, it is a prime number.
public class Prog2{ public static void main(String[] args){ int m = 1; int n = 1000; int count = 0; //Number of statistical primes for(int i=m;i<n;i++){ if(isPrime(i)){ count++; System.out.print(i+" "); if(count%10==0){ System.out.println(); } } } System.out.println(); System.out.println("stay"+m+"and"+n+"Shared between"+count+"Prime number"); } //Judgement prime private static boolean isPrime(int n){ boolean flag = true; if(n==1) flag = false; else{ for(int i=2;i<=Math.sqrt(n);i++){ if((n%i)==0 || n==1){ flag = false; break; } else flag = true; } } return flag; } }
3. Number of daffodils
Print out all the "daffodils". The so-called "daffodils" refers to a three digit number, and the sum of each digit cube is equal to the number itself. For example, 153 is a "daffodil number", because 153 = the third power of 1 + the third power of 5 + the third power of 3.
Program analysis: use the for loop to control 100-999 numbers, and each number is decomposed into bits, tens and hundreds.
public class Prog3{ public static void main(String[] args){ for(int i=100;i<1000;i++){ if(isLotus(i)) System.out.print(i+" "); } System.out.println(); } //Judge the number of daffodils private static boolean isLotus(int lotus){ int m = 0; int n = lotus; int sum = 0; m = n/100; n -= m*100; sum = m*m*m; m = n/10; n -= m*10; sum += m*m*m + n*n*n; if(sum==lotus) return true; else return false; } }
4. Decomposition quality factor
Decompose a positive integer into prime factors. For example, enter 90 and print out 90 = 233 * 5.
Program analysis: to decompose the prime factor of n, first find a minimum prime number k, and then complete the following steps:
(1) If the prime number is exactly equal to n, it means that the process of decomposing the prime factor has ended, and you can print it out.
(2) If n < > k, but n can be divided by K, print out the value of K, divide n by the quotient of K as a new positive integer n, and repeat the first step.
(3) If n cannot be divided by k, repeat the first step with k+1 as the value of k.
public class Prog4{ public static void main(String[] args){ int n = 13; decompose(n); } private static void decompose(int n){ System.out.print(n+"="); for(int i=2;i<n+1;i++){ while(n%i==0 && n!=i){ n/=i; System.out.print(i+"*"); } if(n==i){ System.out.println(i); break; } } } }
5. Use of conditional operators
Use the nesting of conditional operators to complete this problem: students with academic achievement > = 90 points are represented by A, those with 60-89 points are represented by B, and those with less than 60 points are represented by C.
Program analysis: (a > b)? a: B this is a basic example of conditional operators.
public class Prog5{ public static void main(String[] args){ int n = -1; try{ n = Integer.parseInt(args[0]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Please enter grade"); return; } grade(n); } //Grade calculation private static void grade(int n){ if(n>100 || n<0) System.out.println("Invalid input"); else{ String str = (n>=90)?"Points belong to A etc.":((n>60)?"Points belong to B etc.":"Points belong to C etc."); System.out.println(n+str); } } }
6. Common divisor and common multiple
Enter two positive integers m and n to find their maximum common divisor and minimum common multiple.
Program analysis: rolling method is used.
public class Prog6{ public static void main(String[] args){ int m,n; try{ m = Integer.parseInt(args[0]); n = Integer.parseInt(args[1]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Incorrect input"); return; } max_min(m,n); } //Find the greatest common divisor and the least common multiple private static void max_min(int m, int n){ int temp = 1; int yshu = 1; int bshu = m*n; if(n<m){ temp = n; n = m; m = temp; } while(m!=0){ temp = n%m; n = m; m = temp; } yshu = n; bshu /= n; System.out.println(m+"and"+n+"The maximum common divisor of is"+yshu); System.out.println(m+"and"+n+"The least common multiple of is"+bshu); } }
7. Count the number of types in the string
Enter a line of characters and count the number of English letters, spaces, numbers and other characters.
Program analysis: using the while statement, the condition is that the input character is not '\ n'
import java.util.Scanner; public class Prog7_1{ public static void main(String[] args){ System.out.print("Please enter a string of characters:"); Scanner scan = new Scanner(System.in); String str = scan.nextLine();//Converts a line of characters to a string scan.close(); count(str); } //Count the number of characters entered private static void count(String str){ String E1 = "[\u4e00-\u9fa5]";//chinese characters String E2 = "[a-zA-Z]"; String E3 = "[0-9]"; String E4 = "\\s";//Space int countChinese = 0; int countLetter = 0; int countNumber = 0; int countSpace = 0; int countOther = 0; char[] array_Char = str.toCharArray();//Convert string to character array String[] array_String = new String[array_Char.length];//Chinese characters can only be treated as strings for(int i=0;i<array_Char.length;i++) array_String[i] = String.valueOf(array_Char[i]); //Traverses the elements in a string array for(String s:array_String){ if(s.matches(E1)) countChinese++; else if(s.matches(E2)) countLetter++; else if(s.matches(E3)) countNumber++; else if(s.matches(E4)) countSpace++; else countOther++; } System.out.println("Number of Chinese characters entered:"+countChinese); System.out.println("Number of letters entered:"+countLetter); System.out.println("Number of numbers entered:"+countNumber); System.out.println("Number of spaces entered:"+countSpace); System.out.println("Number of other characters entered:"+countSpace); } } import java.util.*; public class Prog7_2{ public static void main(String[] args){ System.out.println("Please enter a line of characters:"); Scanner scan = new Scanner(System.in); String str = scan.nextLine(); scan.close(); count(str); } //Statistics input characters private static void count(String str){ List<String> list = new ArrayList<String>(); char[] array_Char = str.toCharArray(); for(char c:array_Char) list.add(String.valueOf(c));//Add characters as strings to the list table Collections.sort(list);//sort for(String s:list){ int begin = list.indexOf(s); int end = list.lastIndexOf(s); //End of index count characters if(list.get(end)==s) System.out.println("character'"+s+"'have"+(end-begin+1)+"individual"); } } }
8. Find the value of s=a+aa+aaa+aaaa+aa... A
Find the value of s=a+aa+aaa+aaaa+aa... A, where a is a number. For example, 2 + 22 + 222 + 2222 + 22222 (at this time, a total of 5 numbers are added), and the addition of several numbers is controlled by the keyboard.
Program analysis: the key is to calculate the value of each item.
import java.util.Scanner; public class Prog8{ public static void main(String[] args){ System.out.print("seek s=a+aa+aaa+aaaa+...Value of, please enter a Value of:"); Scanner scan = new Scanner(System.in).useDelimiter("\\s*");//Space as separator int a = scan.nextInt(); int n = scan.nextInt(); scan.close();//Turn off the scanner System.out.println(expressed(2,5)+add(2,5)); } //Summation expression private static String expressed(int a,int n){ StringBuffer sb = new StringBuffer(); StringBuffer subSB = new StringBuffer(); for(int i=1;i<n+1;i++){ subSB = subSB.append(a); sb = sb.append(subSB); if(i<n) sb = sb.append("+"); } sb.append("="); return sb.toString(); } //Sum private static long add(int a,int n){ long sum = 0; long subSUM = 0; for(int i=1;i<n+1;i++){ subSUM = subSUM*10+a; sum = sum+subSUM; } return sum; } }
9. Completion of specified range
If a number is exactly equal to the sum of its factors, it is called "perfect". For example, 6 = 1 + 2 + 3 Program to find all completions within 1000.
public class Prog9{ public static void main(String[] args){ int n = 10000; compNumber(n); } //Perfect number private static void compNumber(int n){ int count = 0; System.out.println(n+"Completion within:"); for (int i = 1; i <= 10000; i++) { int temp = 0;// Define the sum of factors variable for (int n = 1; n < i / 2 + 1; n++) { if (i % n == 0) { temp += n;// Divisible divisor is added to temp } } if (temp == i) {// If the sum of the factors is equal to the original number, it means that it is complete System.out.println(i + " ");// Output completion } } } }
10. Inverse index calculation
A ball falls freely from a height of 100 meters and jumps back to half of the original height after each landing; How many meters will it pass on the 10th landing? How high is the 10th rebound?
import java.util.Scanner; public class Prog10{ public static void main(String[] args){ System.out.print("Please enter the height of the small ball when landing and the number of times to solve:"); Scanner scan = new Scanner(System.in).useDelimiter("\\s"); int h = scan.nextInt(); int n = scan.nextInt(); scan.close(); distance(h,n); } //The distance and rebound height of the small ball falling from h height after n rebounds private static void distance(double h,int n){ double length = 0; for(int i=0;i<n;i++){ length += h; h *=0.5 ; length += h; } System.out.println("After the first"+n+"After rebounds, the ball passes through"+length+"Meters,"+"The first"+n+"The secondary rebound height is"+h+"rice"); } }
11. Combination
There are 1, 2, 3 and 4 numbers. How many different three digits can be formed without repeated numbers? How much is it?
Program analysis: the numbers that can be filled in hundreds, tens and single digits are 1, 2, 3 and 4. After all permutations are formed, the permutations that do not meet the conditions are removed.
public class Prog11{ public static void main(String[] args){ int count = 0; int n = 0; for(int i=1;i<5;i++){ for(int j=1;j<5;j++){ if(j==i) continue; for(int k=1;k<5;k++){ if(k!=i && k!=j){ n = i*100+j*10+k; System.out.print(n+" "); if((++count)%5==0) System.out.println(); } } } } System.out.println(); System.out.println("Total number of qualified:"+count+"individual"); } }
12. Gradient calculation
The bonus paid by the enterprise is based on the profit commission. When the profit (I) is less than or equal to 100000 yuan, the bonus can be increased by 10%; When the profit is higher than 100000 yuan and lower than 200000 yuan, the part lower than 100000 yuan shall be deducted by 10%, and the part higher than 100000 yuan shall be deducted by 7.5%; Between 200000 and 400000 yuan, the part higher than 200000 yuan can be deducted by 5%; 3% commission can be given for the part higher than 400000 yuan between 400000 and 600000 yuan; When it is between 600000 and 1 million yuan, the part higher than 600000 yuan can be deducted by 1.5%. When it is higher than 1 million yuan, the part higher than 1 million yuan can be deducted by 1%. Enter the profit I of the current month from the keyboard to calculate the total amount of bonus to be paid?
Program analysis: please use the number axis to divide and locate. Note that the bonus should be defined as a growth integer.
import java.io.*; public class Prog12{ public static void main(String[] args){ System.out.print("Please enter current profit:"); long profit = Long.parseLong(key_Input()); System.out.println("Bonus payable:"+bonus(profit)); } //Accept input from the keyboard private static String key_Input(){ String str = null; BufferedReader bufIn = new BufferedReader(new InputStreamReader(System.in)); try{ str = bufIn.readLine(); }catch(IOException e){ e.printStackTrace(); }finally{ try{ bufIn.close(); }catch(IOException e){ e.printStackTrace(); } } return str; } //Calculate bonus private static long bonus(long profit){ long prize = 0; long profit_sub = profit; if(profit>1000000){ profit = profit_sub-1000000; profit_sub = 1000000; prize += profit*0.01; } if(profit>600000){ profit = profit_sub-600000; profit_sub = 600000; prize += profit*0.015; } if(profit>400000){ profit = profit_sub-400000; profit_sub = 400000; prize += profit*0.03; } if(profit>200000){ profit = profit_sub-200000; profit_sub = 200000; prize += prize*0.05; } if(profit>100000){ profit = profit_sub-100000; profit_sub = 100000; prize += profit*0.075; } prize += profit_sub*0.1; return prize; } }
13. Seeking unknowns
An integer is a complete square number after adding 100, and a complete square number after adding 168. What is the number?
Program analysis: if it is judged within 100000, add 100 to the number before square, and then add 268 to the number before square. If the result after square meets the following conditions, it is the result.
public class Prog13{ public static void main(String[] args){ int n=0; for(int i=0;i<100001;i++){ if(isCompSqrt(i+100) && isCompSqrt(i+268)){ n = i; break; } } System.out.println("The number required is:"+n); } //Judge complete square private static boolean isCompSqrt(int n){ boolean isComp = false; for(int i=1;i<Math.sqrt(n)+1;i++){ if(n==Math.pow(i,2)){ isComp = true; break; } } return isComp; } }
14. Date calculation
Enter a day of a month of a year to judge which day of the year this day is?
Program analysis: take March 5 as an example, you should add up the of the first two months, and then add 5 days, that is, the day of the year. In special cases, when the leap year and the input month is greater than 3, you need to consider adding one more day.
import java.util.Scanner; public class Prog14{ public static void main(String[] args){ Scanner scan = new Scanner(System.in).useDelimiter("\\D");//Match non numeric System.out.print("Please enter the current date (year)-month-(day):"); int year = scan.nextInt(); int month = scan.nextInt(); int date = scan.nextInt(); scan.close(); System.out.println("Today is"+year+"The second day of the year"+analysis(year,month,date)+"day"); } //Judgment days private static int analysis(int year, int month, int date){ int n = 0; int[] month_date = new int[] {0,31,28,31,30,31,30,31,31,30,31,30}; if((year%400)==0 || ((year%4)==0)&&((year%100)!=0)) month_date[2] = 29; for(int i=0;i<month;i++) n += month_date[i]; return n+date; } }
15. Sorting
Enter three integers x, y and Z. please output these three numbers from small to large.
Program analysis: we try to put the smallest number on X, first compare x with y, if x > y, exchange the values of X and y, and then compare x with z. if x > z, exchange the values of X and z, so as to minimize X.
import java.util.Scanner; public class Prog15{ public static void main(String[] args){ Scanner scan = new Scanner(System.in).useDelimiter("\\D"); System.out.print("Please enter three numbers:"); int x = scan.nextInt(); int y = scan.nextInt(); int z = scan.nextInt(); scan.close(); System.out.println("Sorting results:"+sort(x,y,z)); } //Compare the size of two numbers private static String sort(int x,int y,int z){ String s = null; if(x>y){ int t = x; x = y; y = t; } if(x>z){ int t = x; x = z; z = t; } if(y>z){ int t = z; z = y; y = t; } s = x+" "+y+" "+z; return s; } }
16. Bubble sorting
Output 9 * 9 formula.
Procedure analysis: Considering branches and columns, there are 9 rows and 9 columns in total, i control row and j control column.
public class Prog16{ public static void main(String[] args){ for(int i=1;i<10;i++){ for(int j=1;j<i+1;j++) System.out.print(j+"*"+i+"="+(j*i)+" "); System.out.println(); } } }
17. Backstepping calculation
The monkey ate peaches: on the first day, the monkey picked several peaches and ate half of them immediately. He was not addicted. He ate one more. The next morning, he ate half of the remaining peaches and one more. After that, I ate the remaining half and one every morning. When I wanted to eat again on the 10th morning, I saw that there was only one peach left. Ask how much you picked on the first day.
Program analysis: adopt the method of reverse thinking and infer from back to front.
public class Prog17{ public static void main(String[] args){ int m = 1; for(int i=10;i>0;i--) m = 2*m + 2; System.out.println("The little monkeys picked it together"+m+"Peach"); } }
18. Array calculation
The two table tennis teams play three each. Team a consists of a, B and c, and team B consists of x, y and Z. Lots have been drawn to decide the list of matches. The players were asked about the list of matches. A says he doesn't compete with x, c says he doesn't compete with x and Z. please program to find out the list of players of the three teams.
import java.util.ArrayList; public class Prog18{ String a,b,c;//Team a members public static void main(String[] args){ String[] racer = {"x","y","z"};//Team B members ArrayList<Prog18> arrayList = new ArrayList<Prog18>(); for(int i=0;i<3;i++) for(int j=0;j<3;j++) for(int k=0;k<3;k++){ Prog18 prog18 = new Prog18(racer[i],racer[j],racer[k]); if(!prog18.a.equals(prog18.b) && !prog18.a.equals(prog18.c) && !prog18.b.equals(prog18.c) && !prog18.a.equals("x") && !prog18.c.equals("x") && !prog18.c.equals("z")) arrayList.add(prog18); } for(Object obj:arrayList) System.out.println(obj); } //Construction method private Prog18(String a,String b,String c){ this.a = a; this.b = b ; this.c = c; } public String toString(){ return "a Your opponent is"+a+" "+"b Your opponent is"+b+" "+"c Your opponent is"+c; } }
19. Print the following pattern (diamond)
* *** ****** ******** ****** *** *
Program analysis: first divide the graph into two parts, one rule for the first four lines and one rule for the last three lines. Using the double for loop, the first layer controls the rows and the second layer controls the columns.
public class Prog19{ public static void main(String[] args){ int n = 5; printStar(n); } //Print stars private static void printStar(int n){ //Print top half for(int i=0;i<n;i++){ for(int j=0;j<2*n;j++){ if(j<n-i) System.out.print(" "); if(j>=n-i && j<=n+i) System.out.print("*"); } System.out.println(); } //Print bottom half for(int i=1;i<n;i++){ System.out.print(" "); for(int j=0;j<2*n-i;j++){ if(j<i) System.out.print(" "); if(j>=i && j<2*n-i-1) System.out.print("*"); } System.out.println(); } } }
20. Sequence summation
There is a fractional sequence: 2 / 1, 3 / 2, 5 / 3, 8 / 5, 13 / 8, 21 / 13... Find the sum of the first 20 terms of this sequence.
Program analysis: please grasp the change law of numerator and denominator.
public class Prog20{ public static void main(String[] args){ double n1 = 1; double n2 = 1; double fraction = n1/n2; double Sn = 0; for(int i=0;i<20;i++){ double t1 = n1; double t2 = n2; n1 = t1+t2; n2 = t1; fraction = n1/n2; Sn += fraction; } System.out.print(Sn); } }
21. Seek 1 + 2+ 3!+…+ 20! Sum of
Program analysis: This program only turns accumulation into cumulative multiplication.
public class Prog21{ public static void main(String[] args){ long sum = 0; for(int i=0;i<20;i++) sum += factorial(i+1); System.out.println(sum); } //Factorial private static long factorial(int n){ int mult = 1; for(int i=1;i<n+1;i++) mult *= i; return mult; } }
22. Use the recursive method to find 5!.
Program analysis: recursive formula: fn=fn_1*4!
public class Prog22{ public static void main(String[] args){ System.out.println(fact(10)); } //Recursive factorization private static long fact(int n){ if(n==1) return 1; else return fact(n-1)*n; } }
23. Recursive calculation
Five people sat together and asked how old the fifth person was? He said he was two years older than the fourth man. Asked the age of the fourth person, he said that he was 2 years older than the third person. Ask the third person and say that he is two years older than the second. Ask the second person and say that he is two years older than the first. Finally, the first person was asked. He said he was 10 years old. How old is the fifth person?
Program analysis: using the recursive method, recursion is divided into two stages: recursive and recursive. To know the age of the fifth person, you need to know the age of the fourth person, and so on, push it to the first person (10 years old), and then push it back.
public class Prog23{ public static void main(String[] args){ System.out.println(getAge(5,2)); } //Ask the age of the m-th comrade private static int getAge(int m,int n){ if(m==1) return 10; else return getAge(m-1,n)+n; } }
24. Reverse printing
Give a positive integer with no more than 5 digits. Requirements: first, find how many digits it is, and second, print out the numbers in reverse order.
public class Prog24{ public static void main(String[] args){ int n = Integer.parseInt(args[0]); int i = 0; int[] a = new int[5]; do{ a[i] = n%10; n /= 10; ++i; }while(n!=0); System.out.print("This is a"+i+"Digits, starting from digits, the digits are:"); for(int j=0;j<i;j++) System.out.print(a[j]+" "); } }
25. Number of palindromes
A 5-digit number to judge whether it is a palindrome number. That is, 12321 is the palindrome number, the number of bits is the same as 10000 bits, and the number of tens is the same as thousands.
import java.io.*; public class Prog25{ public static void main(String[] args){ int n = 0; System.out.print("Please enter a 5-digit number:"); BufferedReader bufin = new BufferedReader(new InputStreamReader(System.in)); try{ n = Integer.parseInt(bufin.readLine()); }catch(IOException e){ e.printStackTrace(); }finally{ try{ bufin.close(); }catch(IOException e){ e.printStackTrace(); } } palin(n); } private static void palin(int n){ int m = n; int[] a = new int[5]; if(n<10000 || n>99999){ System.out.println("The input is not 5 digits!"); return; }else{ for(int i=0;i<5;i++){ a[i] = n%10; n /= 10; } if(a[0]==a[4] && a[1]==a[3]) System.out.println(m+"Is a palindrome number"); else System.out.println(m+"Not palindromes"); } } }
26. Matching words
Please enter the first letter of the day of the week to judge the day of the week. If the first letter is the same, continue to judge the second letter.
Program analysis: it is better to use the situation statement. If the first letter is the same, judge the second letter with the situation statement or if statement.
import java.io.*; public class Prog26{ public static void main(String[] args){ String str = new String(); BufferedReader bufIn = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter the first two to four letters of the English word of the week):"); try{ str = bufIn.readLine(); }catch(IOException e){ e.printStackTrace(); }finally{ try{ bufIn.close(); }catch(IOException e){ e.printStackTrace(); } } week(str); } private static void week(String str){ int n = -1; if(str.trim().equalsIgnoreCase("Mo") || str.trim().equalsIgnoreCase("Mon") || str.trim().equalsIgnoreCase("Mond")) n = 1; if(str.trim().equalsIgnoreCase("Tu") || str.trim().equalsIgnoreCase("Tue") || str.trim().equalsIgnoreCase("Tues")) n = 2; if(str.trim().equalsIgnoreCase("We") || str.trim().equalsIgnoreCase("Wed") || str.trim().equalsIgnoreCase("Wedn")) n = 3; if(str.trim().equalsIgnoreCase("Th") || str.trim().equalsIgnoreCase("Thu") || str.trim().equalsIgnoreCase("Thur")) n = 4; if(str.trim().equalsIgnoreCase("Fr") || str.trim().equalsIgnoreCase("Fri") || str.trim().equalsIgnoreCase("Frid")) n = 5; if(str.trim().equalsIgnoreCase("Sa") || str.trim().equalsIgnoreCase("Sat") || str.trim().equalsIgnoreCase("Satu")) n = 2; if(str.trim().equalsIgnoreCase("Su") || str.trim().equalsIgnoreCase("Sun") || str.trim().equalsIgnoreCase("Sund")) n = 0; switch(n){ case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 0: System.out.println("Sunday"); break; default: System.out.println("Wrong input!"); break; } } }
27. Find prime numbers within 100
public class Prog27{ public static void main(String[] args){ int n = 100; System.out.print(n+"Prime within:"); for(int i=2;i<n+1;i++){ if(isPrime(i)) System.out.print(i+" "); } } //Find prime private static boolean isPrime(int n){ boolean flag = true; for(int i=2;i<Math.sqrt(n)+1;i++) if(n%i==0){ flag = false; break; } return flag; } }
28. Sort 10 numbers
Program analysis: the selection method can be used, that is, from the last 9 comparison processes, select the smallest one to exchange with the first element, and so on next time, that is, use the second element to compare with the last 8 and exchange.
public class Prog28{ public static void main(String[] args){ int[] a = new int[]{31,42,21,50,12,60,81,74,101,93}; for(int i=0;i<10;i++){ for(int j=0;j<a.length-i-1;j++){ if(a[j]>a[j+1]){ int temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } for(int i=0;i<a.length;i++){ System.out.print(a[i]+" "); } } }
29. Find the sum of diagonal elements of a 3 * 3 matrix
Program analysis: double for loop control is used to input two-dimensional array, and then a[i][i] is accumulated and output.
public class Prog29{ public static void main(String[] args){ int[][] a = new int[][] {{100,2,3,},{4,5,6},{17,8,9}}; matrSum(a); } private static void matrSum(int[][] a){ int sum1 = 0; int sum2 = 0; for(int i=0;i<a.length;i++) for(int j=0;j<a[i].length;j++){ if(i==j) sum1 += a[i][j]; if(j==a.length-i-1) sum2 += a[i][j]; } System.out.println("The sum of the diagonals of the matrix is:"+sum1+"and"+sum2); } }
30. Comparison and sorting
There is an ordered array. Now enter a number and ask to insert it into the array according to the original law.
Program analysis: first judge whether this number is greater than the last number, and then consider inserting the number in the middle. After inserting, the number after this element will move back one position in turn.
import java.util.Scanner; public class Prog30{ public static void main(String[] args){ int[] A = new int[]{0,8,7,5,9,1,2,4,3,12}; int[] B = sort(A); print(B); System.out.println(); System.out.print("Please enter an array of 10 numbers:"); Scanner scan = new Scanner(System.in); int a = scan.nextInt(); scan.close(); int[] C = insert(a,B); print(C); } //Select sort private static int[] sort(int[] A){ int[] B = new int[A.length]; for(int i=0;i<A.length-1;i++){ int min = A[i]; for(int j=i+1;j<A.length;j++){ if(min>A[j]){ int temp = min; min = A[j]; A[j] = temp; } B[i] = min; } } B[A.length-1] = A[A.length-1]; return B; } //Print private static void print(int[] A){ for(int i=0;i<A.length;i++) System.out.print(A[i]+" "); } //Insert number private static int[] insert(int a,int[] A){ int[] B = new int[A.length+1]; for(int i=A.length-1;i>0;i--) if(a>A[i]){ B[i+1] = a; for(int j=0;j<=i;j++) B[j] = A[j]; for(int k=i+2;k<B.length;k++) B[k] = A[k-1]; break; } return B; } }
31. Output an array in reverse order.
Program analysis: exchange the first with the last.
public class Prog31{ public static void main(String[] args){ int[] A = new int[]{1,2,3,4,5,6,7,8,9,}; print(A); System.out.println(); int[] B = reverse(A); print(B); } private static int[] reverse(int[] A){ for(int i=0;i<A.length/2;i++){ int temp = A[A.length-i-1]; A[A.length-i-1] = A[i]; A[i] = temp; } return A; } private static void print(int[] A){ for(int i=0;i<A.length;i++) System.out.print(A[i]+" "); } }
32. Take 4-7 bits of an integer a from the right end.
Program analysis: it can be considered as follows:
(1) First shift a 4 bits to the right.
(2) Set a number whose lower 4 bits are all 1 and the rest are all 0. Available (0 < < 4)
(3) Perform the & operation on the above two.
import java.util.Scanner; public class Prog32{ public static void main(String[] msg){ //Enter a long integer Scanner scan = new Scanner(System.in); long l = scan.nextLong(); scan.close(); //The following intercepted characters String str = Long.toString(l); char[] ch = str.toCharArray(); int n = ch.length; if(n<7) System.out.println("The number entered is less than 7 digits!"); else System.out.println("Intercepted 4~7 Digit:"+ch[n-7]+ch[n-6]+ch[n-5]+ch[n-4]); } }
33. Print out Yang Hui triangle (10 lines are required, as shown in the figure below)
Program analysis:
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1
public class Prog33{ public static void main(String[] args){ int[][] n = new int[10][21]; n[0][10] = 1; for(int i=1;i<10;i++) for(int j=10-i;j<10+i+1;j++) n[i][j] = n[i-1][j-1]+n[i-1][j+1]; for(int i=0;i<10;i++){ for(int j=0;j<21;j++){ if(n[i][j]==0) System.out.print(" "); else{ if(n[i][j]<10) System.out.print(" "+n[i][j]);//Spaces are needed for beauty else if(n[i][j]<100) System.out.print(" "+n[i][j]); else System.out.print(n[i][j]); } } System.out.println(); } } }
34. Input three numbers a, B and C and output them in order of size.
Program analysis: using pointer method.
import java.util.Scanner; public class Prog34{ public static void main(String[] args){ System.out.print("Please enter 3 numbers:"); Scanner scan = new Scanner(System.in).useDelimiter("\\s"); int a = scan.nextInt(); int b = scan.nextInt(); int c = scan.nextInt(); scan.close(); if(a<b){ int t = a; a = b; b = t; } if(a<c){ int t = a; a = c; c = t; } if(b<c){ int t = b; b = c; c = t; } System.out.println(a+" "+b+" "+c); } }
35. Select sort
Input array, the largest is exchanged with the first element, the smallest is exchanged with the last element, and the output array.
import java.util.Scanner; public class Prog35{ public static void main(String[] args){ System.out.print("Please enter a group number:"); Scanner scan = new Scanner(System.in).useDelimiter("\\s"); int[] a = new int[50]; int m = 0; while(scan.hasNextInt()){ a[m++] = scan.nextInt(); } scan.close(); int[] b = new int[m]; for(int i=0;i<m;i++) b[i] = a[i]; for(int i=0;i<b.length;i++) for(int j=0;j<b.length-i-1;j++) if(b[j]<b[j+1]){ int temp = b[j]; b[j] = b[j+1]; b[j+1] = temp; } for(int i=0;i<b.length;i++) System.out.print(b[i]+" "); } }
36. Exchange position
There are n integers, so that the previous numbers move m positions backward in sequence, and the last m numbers become the first m numbers
import java.util.Scanner; public class Prog36{ public static void main(String[] args){ final int N = 10; System.out.print("Please enter an array of 10 numbers:"); Scanner scan = new Scanner(System.in); int[] a = new int[N]; for(int i=0;i<a.length;i++) a[i] = scan.nextInt(); System.out.print("Please enter a number less than 10:"); int m = scan.nextInt(); scan.close(); int[] b = new int[m]; int[] c = new int[N-m]; for(int i=0;i<m;i++) b[i] = a[i]; for(int i=m,j=0;i<N;i++,j++) c[j] = a[i]; for(int i=0;i<N-m;i++) a[i] = c[i]; for(int i=N-m,j=0;i<N;i++,j++) a[i] = b[j]; for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); } }
37. Ranking problem
There are n people in a circle and number them in sequence. Start counting from the first person (counting from 1 to 3). Anyone who reports to 3 quits the circle and asks what number is left last.
import java.util.Scanner; public class Prog37{ public static void main(String[] args){ System.out.print("Please enter an integer:"); Scanner scan = new Scanner(System.in); int n = scan.nextInt(); scan.close(); //Define an array variable to identify whether someone is still in the loop boolean[] isIn = new boolean[n]; for(int i=0;i<isIn.length;i++) isIn[i] = true; //Define the number of people in the circle, number of reports and index int inCount = n; int countNum = 0; int index = 0; while(inCount>1){ if(isIn[index]){ countNum++; if(countNum==3){ countNum = 0; isIn[index] = false; inCount--; } } index++; if(index==n) index = 0; } for(int i=0;i<n;i++) if(isIn[i]) System.out.println("What is left is:"+(i+1)); } }
38. Calculate the total length of the string
Write a function, find the length of a string, enter the string in the main function, and output its length.
import java.util.Scanner; public class Prog38{ public static void main(String[] args){ System.out.print("Please enter a string of characters:"); Scanner scan = new Scanner(System.in).useDelimiter("\\n"); String strIn = scan.next(); scan.close(); char[] ch = strIn.toCharArray(); System.out.println(strIn+"common"+(ch.length-1)+"Characters"); } }
39. Summation
Write a function. When the input n is an even number, call the function to find 1 / 2 + 1 / 4 +... + 1/n. when the input n is an odd number, call the function 1 / 1 + 1 / 3 +... + 1/n (using the pointer function)
import java.util.Scanner; public class Prog39{ public static void main(String[] args){ System.out.print("Please enter an integer:"); Scanner scan = new Scanner(System.in); int n = scan.nextInt(); scan.close(); if(n%2==0) System.out.println("result:"+even(n)); else System.out.println("result:"+odd(n)); } //Odd number static double odd(int n){ double sum = 0; for(int i=1;i<n+1;i+=2){ sum += 1.0/i; } return sum; } //even numbers static double even(int n){ double sum = 0; for(int i=2;i<n+1;i+=2){ sum += 1.0/i; } return sum; } }
40. String sorting.
public class Prog40{ public static void main(String[] args){ String[] str = {"abc","cad","m","fa","f"}; for(int i=str.length-1;i>=1;i--){ for(int j=0;j<=i-1;j++){ if(str[j].compareTo(str[j+1])<0){ String temp = str[j]; str[j] = str[j+1]; str[j+1] = temp; } } } for(String subStr:str) System.out.print(subStr+" "); } }
41. Recursion
There is a pile of peaches on the beach. Five monkeys share them. The first monkey divided the pile of peach credentials into five, one more, and the monkey threw the one more into the sea and took one. The second monkey divided the remaining peaches into five parts on average, and one more. It also threw one more into the sea and took one. The third, fourth and fifth monkeys did so. How many peaches were there on the beach?
public class Prog41{ public static void main(String[] args){ int n; n = fun(0); System.out.println("Originally"+n+"A peach"); } private static int fun(int i){ if(i==5) return 1; else return fun(i+1)*5+1; } }Copy code
42.809??=800??+9*??+1
Where?? Represents two digits, 8?? The result is double digits, 9?? The result is 3 digits. Please?? Represents two digits, and 809 *?? Results after.
public class Prog42{ public static void main(String[] args){ int n = 0; boolean flag = false; for(int i=10;i<100;i++) if(809*i==800*i+9*i+1){ flag = true; n = i; break; } if(flag) System.out.println(n); else System.out.println("No qualified number!"); } }
43. Find the odd number that can be composed of 0-7.
public class Prog43{ public static void main(String[] args){ int count = 0; //Declare a number consisting of numbers int n = 8; //Single digit count = n/2; //Double digit count += (n-1)*n/2; //Three digit count += (n-1)*n*n/2; //Four digit count += (n-1)*n*n*n/2; //Five digits count += (n-1)*n*n*n*n/2; //Six digit count += (n-1)*n*n*n*n*n/2; //Seven digits count += (n-1)*n*n*n*n*n*n/2; System.out.println("0-7 Odd numbers that can be composed:"+count); } }
44. An even number can always be expressed as the sum of two prime numbers.
import java.util.Scanner; public class Prog44{ public static void main(String[] args){ System.out.print("Please enter an even number:"); Scanner scan = new Scanner(System.in); int n = scan.nextInt(); scan.close(); if(n%2!=0){ System.out.println("The number you entered is not even!"); return; } twoAdd(n); } //Even numbers are decomposed into the sum of prime numbers private static void twoAdd(int n){ for(int i=2;i<n/2+1;i++){ if(isPrime(i)&&isPrime(n-i)){ System.out.println(n+"="+(i)+"+"+(n-i)); break; } } } //Judgement prime private static boolean isPrime(int m){ boolean flag = true; for(int i=2;i<Math.sqrt(m)+1;i++){ if(m%i==0){ flag = false; break; } } return flag; } }
45. Judge how many 9s a prime number can be divided by
import java.util.Scanner; public class Prog45{ public static void main(String[] args){ System.out.print("Please enter a number:"); Scanner scan = new Scanner(System.in); long l = scan.nextLong(); long n = l; scan.close(); int count = 0; while(n>8){ n /= 9; count++; } System.out.println(l+"Can be"+count+"Divide by nine."); } }
46. Two string linkers
public class Prog46{ public static void main(String[] args){ String str1 = "lao lee"; String str2 = "Ox knife"; String str = str1+str2; System.out.println(str); } }
47. Print exercise
Read the integer value of 7 numbers (1-50). For each value read, the program prints out the number of * of the value.
import java.util.Scanner; public class Prog47{ public static void main(String[] args){ System.out.print("Please enter 7 integers(1-50): "); Scanner scan = new Scanner(System.in); int n1 = scan.nextInt(); int n2 = scan.nextInt(); int n3 = scan.nextInt(); int n4 = scan.nextInt(); int n5 = scan.nextInt(); int n6 = scan.nextInt(); int n7 = scan.nextInt(); scan.close(); printStar(n1); printStar(n2); printStar(n3); printStar(n4); printStar(n5); printStar(n6); printStar(n7); } static void printStar(int m){ System.out.println(m); for(int i=0;i<m;i++) System.out.print("*"); System.out.println(); } }
48. Encryption algorithm
A company uses a public telephone to transmit data. The data is a four digit integer and is encrypted in the transmission process. The encryption rules are as follows: add 5 to each number, then replace the number with the remainder of sum divided by 10, and then exchange the first and fourth bits, and the second and third bits.
public class Prog48{ public static void main(String[] args){ int n = 1234; int[] a = new int[4]; for(int i=3;i>=0;i--){ a[i] = n%10; n /= 10; } for(int i=0;i<4;i++) System.out.print(a[i]); System.out.println(); for(int i=0;i<a.length;i++){ a[i] += 5; a[i] %= 10; } int temp1 = a[0]; a[0] = a[3]; a[3] = temp1; int temp2 = a[1]; a[1] = a[2]; a[2] = temp2; for(int i=0;i<a.length;i++) System.out.print(a[i]); } }
49. Calculate the number of occurrences of substrings in the string
public class Prog49{ public static void main(String[] args){ String str = "I come from County DingYuan Province AnHui."; char[] ch = str.toCharArray(); int count = 0; for(int i=0;i<ch.length;i++){ if(ch[i]==' ') count++; } count++; System.out.println("share"+count+"String (s)"); } }
50. Average
There are five students. Each student has the scores of three courses. Input the above data from the keyboard (including student number, name and scores of three courses), calculate the average score, and store the original data and the calculated average score in the disk file "study".
import java.io.*; public class Prog50{ //Define student model String[] number = new String[5]; String[] name = new String[5]; float[][] grade = new float[5][3]; float[] sum = new float[5]; public static void main(String[] args) throws Exception{ Prog50 stud = new Prog50(); stud.input(); stud.output(); } //Enter student number, name and grade void input() throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Input status identification boolean isRecord = true; while(isRecord){ try{ for(int i=0;i<5;i++){ System.out.print("Please enter student number:"); number[i] = br.readLine(); System.out.print("Please enter your name:"); name[i] = br.readLine(); for(int j=0;j<3;j++){ System.out.print("Please enter page"+(j+1)+"Course score:"); grade[i][j] = Integer.parseInt(br.readLine()); } System.out.println(); sum[i] = grade[i][0]+grade[i][1]+grade[i][2]; } isRecord = false; }catch(NumberFormatException e){ System.out.println("Please enter a number!"); } } } //output file void output() throws IOException{ FileWriter fw = new FileWriter("E://java50//stud.txt"); BufferedWriter bw = new BufferedWriter(fw); bw.write("No. "+"Name "+"grade1 "+"grade2 "+"grade3 "+"average"); bw.newLine(); for(int i=0;i<5;i++){ bw.write(number[i]); bw.write(" "+name[i]); for(int j=0;j<3;j++) bw.write(" "+grade[i][j]); bw.write(" "+(sum[i]/5)); bw.newLine(); } bw.close(); } }