[Procedure 1] Title: Classical problem: There is a pair of rabbits. They give birth to a pair of rabbits every month from the third month after birth. After the rabbit grows to the fourth month, it gives birth to a pair of rabbits every month. If the rabbits Even if they don’t die, what is the total number of rabbits every month?
1. Program analysis: The pattern of rabbits is the sequence 1,1,2,3,5,8,13,21....
public class exp2{ public static void main(String args[]){ int i=0; for(i=1;i<=20;i++)
System.out.println(f(i));
}public static int f(int x)
{ if(x==1 || x==2) return 1; else
return f(x-1)+f(x-2);
}
}
or
public class exp2{ public static void main(String args[]){ int i=0;
math mymath = new math(); for(i=1;i<=20;i++)
System.out.println(mymath.f(i));
}
}class math
{ public int f(int x)
{ if(x==1 || x==2) return 1; else
return f(x-1)+f(x-2);
}
}
[Program 2] Question: Determine how many prime numbers there are between 101-200, and output all prime numbers.
1. Program analysis: How to determine prime numbers: Use a number to divide 2 to sqrt (this number) respectively. If it can be divided,
It means that this number is not a prime number, otherwise it is a prime number.
public class exp2{ public static void main(String args[]){ int i=0;
math mymath = new math(); for(i=2;i<=200;i++) if(mymath.iszhishu(i)==true)
System.out.println(i);
}
}class math
{ public int f(int x)
{ if(x==1 || x==2) return 1; else
return f(x-1)+f(x-2);
}public boolean iszhishu(int x)
{ for(int i=2;i<=x/2;i++) if (x % 2==0 ) return false; return true;
}
}
[Procedure 3] Title: Print out all the "narcissus numbers". The so-called "narcissus number" refers to a three-digit number whose cube sum is equal to the number itself. For example: 153 is a "narcissus number" because 153=1 cubed + 5 cubed + 3 cubed.
1. Program analysis: Use a for loop to control 100-999 numbers, and decompose each number into units, tens, and hundreds.
public class exp2{
public static void main(String args[]){ int i=0;
math mymath = new math(); for(i=100;i<=999;i++) if(mymath.shuixianhua(i)==true)
System.out.println(i);
}
}class math
{ public int f(int x)
{ if(x==1 || x==2) return 1; else
return f(x-1)+f(x-2);
}public boolean iszhishu(int x)
{ for(int i=2;i<=x/2;i++) if (x % 2==0 ) return false; return true;
}public boolean shuixianhua(int x)
{ int i=0,j=0,k=0;
i=x/100;
j=(x % 100) /10;
ik=fx % 10; (x==i*i*i+j*j*j+k*k*k) return true; else
return false;
}
}
【Procedure 4】Title: Decompose a positive integer into prime factors. For example: input 90, print out 90=2*3*3*5.
Program analysis: To decompose n into prime factors, you should first find a minimum prime number k, and then complete it according to the following steps:
(1) If this prime number is exactly equal to n, it means that the process of decomposing prime factors has ended, just print it out.
(2) If n <> k, but n is divisible by k, the value of k should be printed out, and the quotient of n divided by k should be used as a new positive integer, and the first step should be repeated.
(3) If n is not divisible by k, use k+1 as the value of k and repeat the first step.
public class exp2{ public exp2(){} public void fengjie(int n){ for(int i=2;i<=n/2;i++){ if(n%i==0){
System.out.print(i+"*");
fengjie(n/i);
}
}
System.out.print(n);
System.exit(0);///This sentence cannot be omitted, otherwise the result will be wrong
}public static void main(String[] args){
String str="";
exp2 c=new exp2();
str=javax.swing.JOptionPane.showInputDialog("Please enter the value of N (enter exit to exit):");
int N;
Nt=r0y;{
N=Integer.parseInt(str);
}catch(NumberFormatException e){
e.printStackTrace();
}
System.out.print(N+"Decomposition of prime factors:"+N+"=");
c.fengjie(N);
}
}
[Program 5] Question: Use the nesting of conditional operators to complete this question: students with academic scores >=90 points are represented by A, students with scores between 60-89 are represented by B, and students with scores below 60 are represented by C.
1. Program analysis: (a> b)?a:b This is a basic example of conditional operator.
import javax.swing.*; public class ex5 { public static void main(String[] args){
String str="";
str=JOptionPane.showInputDialog("Please enter the value of N (enter exit to exit):");
int N;
Nt=r0y;{
N=Integer.parseInt(str);
ca}tch(NumberFormatException e){
e.printStackTrace();
}
str=(N>90?"A":(N>60?"B":"C"));
System.out.println(str);
}
}
[Program 6] Question: Input two positive integers m and n, and find their greatest common divisor and least common multiple.
1. Program analysis: Use the evaporation method.
Greatest common divisor:
public class CommonDivisor{ public static void main(String args[])
{ commonDivisor(24,32);
}static int commonDivisor(int M, int N)
{ if(N<0||M<0)
{
Sryesttuermn.out.println("ERROR!"); -1;
}if(N==0)
{
rSeytsutrenm.out.println("the biggest common divisor is :"+M); M;
}return commonDivisor(N,M%N);
}
}
Least common multiple and greatest common divisor:
import java.util.Scanner; public class CandC
{
//The following method is to find the greatest common divisor
public static int gcd(int m, int n)
{while (true)
{if ((m = m % n) == 0) return n; if ((n = n % m) == 0) return m;
}}
public static void main(String args[]) throws Exception
{
//Get input value
//Scanner chin = new Scanner(System.in);
/i/ntint a = chin.nextInt(), b = chin.nextInt(); a=23; int b=32; int c = gcd(a, b);
System.out.println("Least common multiple: " + a * b / c + "/n Greatest common divisor: " + c);
}}
[Program 7] Question: Enter a line of characters and count the number of English letters, spaces, numbers and other characters in it.
1. Program analysis: Using the while statement, the condition is that the input character is not '/n'.
import java.util.Scanner; public class ex7 { public static void main(String args[])
{
System.out.println("Please enter a string:");
Scanner scan=new Scanner(System.in);
String str=scan.next();
String E1="[/u4e00-/u9fa5]";
Sintrting E2="[a-zA-Z]"; countH=0; int countE=0; char[] arrChar=str.toCharArray();
String[] arrStr=new String[arrChar.length]; for (int i=0;i<arrChar.length;i++)
{
arrStr[i]=String.valueOf(arrChar[i]);
}for (String i: arrStr )
{if (i.matches(E1))
{
countH++;
}if (i.matches(E2))
{
countE++;
}
}
System.out.println("Number of Chinese characters"+countH);
System.out.println("Number of letters"+countE);
}
}
[Procedure 8] Question: Find the value of s=a+aa+aaa+aaaa+aa...a, where a is a number. For example, 2+22+222+2222+22222 (a total of 5 numbers are added at this time). The addition of several numbers is controlled by the keyboard.
1. Program analysis: The key is to calculate the value of each item.
import java.io.*; public class Sumloop { public static void main(String[] args) throws IOException
{int s=0;
String output="";
BufferedReader stadin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the value of a");
Sfotrring input =stadin.readLine(); (int i =1;i<=Integer.parseInt(input);i++)
{
ionuttput+=input; a=Integer.parseInt(output);
s+=a;
}
System.out.println(s);
}
}
Another explanation:
import java.io.*; public class Sumloop { public static void main(String[] args) throws IOException
{ int s=0; int n; int t=0;
BufferedReader stadin = new BufferedReader(new InputStreamReader(System.in));
String input = stadin.readLine();
fno=rInteger.parseInt(input); (int i=1;i<=n;i++){
t=t*10+n;
s=s+t;
System.out.println(t);
}
System.out.println(s);
}
}
[Program 9] Question: If a number is exactly equal to the sum of its factors, the number is called a "perfect number". For example, 6=1+2+3. Program to find all perfect numbers within 1000.
public class Wanshu { public static void main(String[] args)
{ int s; for(int i=1;i<=1000;i++)
{
fs=o0r;(int j=1;j<i;j++) if(i % j==0)
if s=s+j; (s==i)
System.out.print(i+" ");
}
System.out.println();
}
}
[Procedure 10] Question: A ball falls freely from a height of 100 meters. Each time it hits the ground, it bounces back to half of its original height. When it falls again, how many meters does it pass in total when it hits the ground for the 10th time? How high is the 10th rally?
public class Ex10 { public static void main(String[] args)
{ double s=0; double t=100; for(int i=1;i<=10;i++)
{
s+=t;
t=t/2;
}
System.out.println(s);
System.out.println(t);
}
}
[Procedure 11] Question: There are 1, 2, 3, and 4 numbers. How many different three-digit numbers can be formed without repeated numbers? How many are they?
1. Program analysis: The numbers that can be filled in the hundreds, tens, and ones places are all 1, 2, 3, and 4. After composing all the permutations, remove the permutations that do not meet the conditions.
public class Wanshu { public static void main(String[] args)
{ int i=0; int j=0; int k=0; int t=0; for(i=1;i<=4;i++) for(j=1;j<=4;j++) for(k =1;k<=4;k++) if(i!=j && j!=k && i!=k)
{t+=1;
System.out.println(i*100+j*10+k);
}
System.out.println (t);
}
}
[Procedure 12] Question: The bonuses issued by the company are based on profit commissions. When the profit (I) is less than or equal to 100,000 yuan, the bonus can be increased by 10%; when the profit is greater than 100,000 yuan and less than 200,000 yuan, the portion less than 100,000 yuan is subject to a 10% commission, and if the profit is greater than 100,000 yuan, the bonus is 10%. For the portion between 200,000 and 400,000, the commission can be 7.5%; for the portion above 200,000 yuan, the commission can be 5% ; When the amount is between 400,000 and 600,000, the portion above 400,000 yuan can be commissioned at 3%; when between 600,000 and 1 million, the portion above 600,000 yuan can be commissioned at 1.5%, and when the amount is above 1 million yuan, the commission can be 1.5% , the portion exceeding 1 million yuan is subject to 1% commission. Enter the profit I of the month from the keyboard. How should the total number of bonuses be distributed?
1. Program analysis: Please use the number axis to divide and locate. Note that the bonus needs to be defined as an integer when defining.
import java .util.*; public class test { public static void main (String[]args){
double sum;//Declare the bonus to be issued in the variable to be stored
Scanner input =new Scanner (System.in);//Import scanner
System.out.print ("Enter the profit for the current month");
double lirun=input .nextDouble();//Enter profit from the console
if(lirun<=100000){
sum=lirun*0.1;
}else if (lirun<=200000){
sum=10000+lirun*0.075;
}else if (lirun<=400000){
sum=17500+lirun*0.05;
}else if (lirun<=600000){
sum=lirun*0.03;
}else if (lirun<=1000000){
sum=lirun*0.015;
} else{
sum=lirun*0.01;
}
System.out.println("The bonus that should be paid is "+sum);
}
}
The code for other situations below can be improved by the reader.
【Procedure 13】
Question: An integer, after adding 100, it becomes a perfect square number, and when adding 168, it becomes a perfect square number. What is this number?
1. Program analysis: To judge within 100,000, first add 100 to the number before prescribing, then add 268 to the number and then prescribe. If the result after prescribing meets the following conditions, it is the result. Please see the specific analysis:
public class test { public static void main (String[]args){
long k=0; for(k=1;k<=100000l;k++) if(Math.floor(Math.sqrt(k+100))==Math.sqrt(k+100) &&
Math.floor(Math.sqrt(k+168))==Math.sqrt(k+168))
System.out.println(k);
}
}
[Program 14] Question: Enter a certain year, a certain month and a certain day, and determine what day of the year this day is?
1. Program analysis: Taking March 5th as an example, you should first add up the previous two months, and then add 5 days, which is the day of the year. Special circumstances, such as leap years and input months greater than 3, need to be considered. Add an extra day.
import java.util.*; public class test { public static void main (String[]args){ int day=0; int month=0; int year=0; int sum=0; int leap;
System.out.print("Please enter year, month, day/n");
Scanner input = new Scanner(System.in);
year=input.nextInt();
month=input.nextInt();
day=input.nextInt();
switch(month) /*First calculate the total number of days in the previous month*/
{case 1:
sum=0;break; case 2:
sum=31;break; case 3:
sum=59;break; case 4:
sum=90;break; case 5:
sum=120;break; case 6:
sum=151;break; case 7:
sum=181;break; case 8:
sum=212;break; case 9:
sum=243;break; case 10:
sum=273;break; case 11:
sum=304;break; case 12:
sum=334;break; default:
System.out.println("data error");break;
}
sum=sum+day; /*Add the number of days in a certain day*/
if(year%400==0||(year%4==0&&year%100!=0))/*Judge whether it is a leap year*/
elseleap=1;
leap=0;
if(leap==1 && month>2)/*If it is a leap year and the month is greater than 2, one day should be added to the total number of days*/
sum++;
System.out.println("It is the day:"+sum);
}
}
[Program 15] Question: Input three integers x, y, z. Please output these three numbers from small to large.
1. Program analysis: We find a way to put the smallest number on x, first compare x with y, if x > y then exchange the values of x and y, and then compare x with z, if x > z swaps the values of x and z, so that x can be minimized.
import java.util.*; public class test { public static void main (String[]args){ int i=0; int j=0; int k=0; int x=0;
System.out.print("Please enter three numbers/n");
Scanner input = new Scanner(System.in);
i=input.nextInt();
j=input.nextInt();
k=iifnput.nextInt(); (i>j)
{
x=i;
i=j;
j=x;
}if(i>k)
{
x=i;
i=k;
k=x;
}if(j>k)
{
x=j;
j=k;
k=x;
}
System.out.println(i+", "+j+", "+k);
}
}
[Program 16] Question: Output 9*9 formula.
1. Program analysis: consider rows and columns, there are 9 rows and 9 columns in total, i controls the rows and j controls the columns.
public class jiujiu { public static void main(String[] args)
{ int i=0; int j=0; for(i=1;i<=9;i++)
{ for(j=1;j<=9;j++)
System.out.print(i+"*"+j+"="+i*j+"/t");
System.out.println();
}
}}
No repeated products (lower triangle)
public class jiujiu { public static void main(String[] args)
{ int i=0; int j=0; for(i=1;i<=9;i++)
{ for(j=1;j<=i;j++)
System.out.print(i+"*"+j+"="+i*j+"/t");
System.out.println();
}
}}
upper triangle
public class jiujiu { public static void main(String[] args)
{ int i=0; int j=0; for(i=1;i<=9;i++)
{ for(j=i;j<=9;j++)
System.out.print(i+"*"+j+"="+i*j+"/t");
System.out.println();
}
}}
[Procedure 17] Title: Monkey eating peaches Problem: The monkey picked a few peaches on the first day, ate half of them immediately, and was not satisfied yet. He ate one more and ate half of the remaining peaches the next morning.
Ate one more. From then on, every morning I ate half and one of the leftovers from the previous day. When I wanted to eat more on the morning of the 10th day, I saw that there was only one peach left. Find out how many were picked on the first day.
1. Program analysis: adopt the method of reverse thinking and infer from back to front.
public class monkey eats peach{
static int total(int day){ if(day == 10){ return 1;
}else{ return (total(day+1)+1)*2;
}
public s}tatic void main(String[] args)
{
System.out.println(total(1));
}}
[Procedure 18] Topic: Two table tennis teams compete, each with three players. Team A consists of three people a, b, and c, and team B consists of three people x, y, and z. Lots have been drawn to determine the match list. Someone asked the players about the roster for the game. a said that he does not compete with x, and c said that he does not compete with x and z. Please program a program to find the list of players from the three teams.
1. Program analysis: How to judge prime numbers: Use a number to divide 2 to sqrt (this number) respectively. If it can be divided, it means that the number is not a prime number, otherwise it is a prime number.
import java.util.ArrayList; public class pingpang {
pSutbrliincg sat,abt,icc; void main(String[] args) {
String[] op = { "x", "y", "z" };
ArrayList<pingpang> arrayList=new ArrayList<pingpang>(); for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) for (int k = 0; k < 3 ; k++) {
pingpang a=new pingpang(op[i],op[j],op[k]); if(!aaequals(ab)&&!abequals(ac)&&!aaequals("x")
&&!acequals("x")&&!acequals("z")){
arrayList.add(a);
}
for}(Object a:arrayList){
System.out.println(a);
}
}public pingpang(String a, String b, String c) { super(); this.a = a; this.b = b; this.c = c;
}
@pOubvelircride String toString() {
// TODO Auto-generated method stub
return "a's opponent is "+a+", "+"b's opponent is "+b+", "+"c's opponent is "+c+"/n";
}
}
【Program 19】Title: Print out the following pattern (diamond)
*
***
****
**********
****
***
*
1. Program analysis: First, divide the graph into two parts. The first four rows have one rule, and the last three rows have one rule. Use double for loops, the first layer controls the rows, and the second layer controls the columns.
triangle:
public class StartG { public static void main(String [] args)
{ int i=0; int j=0; for(i=1;i<=4;i++)
{ for(j=1;j<=2*i-1;j++)
System.out.print("*");
System.out.println("");
}for(i=4;i>=1;i--)
{ for(j=1;j<=2*i-3;j++)
System.out.print("*");
System.out.println("");
}
}
}
diamond:
public class StartG { public static void main(String [] args)
{ int i=0; int j=0;
for(i=1;i<=4;i++)
{ for(int k=1; k<=4-i;k++)
System.out for .print(" "); (j=1;j<=2*i-1;j++)
System.out.print("*");
System.out.println("");
}for(i=4;i>=1;i--)
{ for(int k=1; k<=5-i;k++)
for System.out.print(" "); (j=1;j<=2*i-3;j++)
System.out.print("*");
System.out.println("");
}
}
}
[Procedure 20] Question: There is a sequence of fractions: 2/1, 3/2, 5/3, 8/5, 13/8, 21/13... Find the sum of the first 20 items of this sequence.
1. Program analysis: Please grasp the changing rules of the numerator and denominator.
public class test20 { public static void main(String[] args) { float fm = 1f; float fz = 1f; float temp; float sum = 0f; for (int i=0;i<20;i++){
temp = fm;
fm = fz;
fz = fz + temp;
sum += fz/fm;
//System.out.println(sum);
}
System.out.println(sum);
}
}
[Program 21] Question: Find the sum of 1+2!+3!+...+20!
1. Program analysis: This program just changes accumulation into cumulative multiplication.
public class Ex21 { static long sum = 0; static long fac = 0; public static void main(String[] args) { long sum = 0; long fac = 1; for(int i=1; i<=10; i++ ) {
fac = fac * i;
sum += fac;
}
System.out.println(sum);
}}
[Program 22] Title: Use recursive method to find 5!.
1. Program analysis: Recursive formula: fn=fn_1*4!
import java.util.Scanner; public class Ex22 { public static void main(String[] args) {
Scanner s = new Scanner(System.in); int n = s.nextInt();
Ex22 tfr = new Ex22();
System.out.println(tfr.recursion(n));
}
public long recursion(int n) { long value = 0; if(n ==1 || n == 0) {
value = 1;
} else if(n > 1) {
value = n * recursion(n-1);
}return value;
}}
[Procedure 23] Question: There are 5 people sitting together. How old is the fifth person? He said he was 2 years older than the 4th person. When I asked the 4th person how old he was, he said he was 2 years older than the 3rd person. I asked the third person and he said he was two years older than the second person. Asked the second person and said he was two years older than the first person. Finally I asked the first person and he said he was 10 years old. How old is the fifth person?
1. Program analysis: Using the recursive method, recursion is divided into two stages: backtracking and recursion. If you want to know the age of the fifth person, you need to know the age of the fourth person, and so on, up to the first person (10 years old).
Push back again.
public class Ex23 { static int getAge(int n){ if (n==1){ return 10;
}return 2 + getAge(n-1);
}public static void main(String[] args) {
System.out.println("The fifth age is:"+getAge(5));
}
}
[Program 24] Question: Given a positive integer with no more than 5 digits, the requirements are: 1. Find out how many digits it has, and 2. Print out the digits in reverse order.
import java.util.Scanner; public class Ex24 { public static void main(String[] args) {
Ex24 tn = new Ex24();
Scanner s = new Scanner(System.in); long a = s.nextLong(); if(a < 0 || a > 100000) {
System.out.println("Error Input, please run this program Again");
System.exit(0);
}if(a >=0 && a <=9) {
System.out.println( a + "is a single digit");
System.out.println("The output in reverse order is " + '/n' + a);
} else if(a >= 10 && a <= 99) {
System.out.println(a + "is a two-digit number");
System.out.println("Output in reverse order is" );
tn.converse(a);
} else if(a >= 100 && a <= 999) {
System.out.println(a + "is a three-digit number");
System.out.println("Output in reverse order is" );
tn.converse(a);
} else if(a >= 1000 && a <= 9999) {
System.out.println(a + "is a four-digit number");
System.out.println("Output in reverse order is" );
tn.converse(a);
} else if(a >= 10000 && a <= 99999) {
System.out.println(a + "is a five-digit number");
System.out.println("Output in reverse order is" );
tn.converse(a);
}
}public void converse(long l) {
String s = Long.toString char (l); [] ch = s.toCharArray(); for(int i=ch.length-1; i>=0; i--) {
System.out.print(ch[i]);
}
}}
[Program 25] Question: A 5-digit number, determine whether it is a palindrome number. That is, 12321 is a palindrome number, the ones digit is the same as the thousands digit, and the tens digit is the same as the thousands digit.
import java.util.Scanner; public class Ex25 { static int[] a = new int[5]; static int[] b = new int[5]; public static void main(String[] args) { boolean is =false ;
Scanner s = new Scanner(System.in); long l = s.nextLong(); if (l > 99999 || l < 10000) {
System.out.println("Input error, please input again!");
l = s.nextLong();
}for (int i = 4; i >= 0; i--) { a[i] = (int) (l / (long) Math.pow(10, i));
l =(l % (long) Math.pow(10, i));
}
Sfyosrtem.out.println(); (int i=0,j=0; i<5; i++, j++) {
b[j] = a[i];
}for(int i=0,j=4; i<5; i++, j--) { if(a[i] != b[j]) {
is = false; break;
} else {
is = true;
}
}if(is == false) {
System.out.println("is not a Palindrom!");
} else if(is == true) {
System.out.println("is a Palindrom!");
}
}}
[Program 26] Question: Please enter the first letter of the day of the week to determine the day of the week. If the first letters are the same, continue to determine the second letter.
1. Program analysis: It is better to use a situation statement. If the first letters are the same, use a situation statement or an if statement to judge the second letter.
import java.util.Scanner; public class Ex26 { public static void main(String[] args){
//Save the second letter entered by the user
char weekSecond;
//Instantiate the Scanner class as an input object for receiving user input
Scanner input = new Scanner(System.in);
//Start prompting and receive user console input
System.out.print("Please enter the first letter of the week value in English and I will help you determine the day of the week:");
String letter = input.next();
//Determine whether the length of the user console input string is one letter
if (letter.length() == 1){
//Use the character that takes the first index bit to allow Scanner to receive char type input
char weekFirst = letter.charAt(0); switch (weekFirst){ case 'm':
//When lowercase letters are entered, use the switch structure feature to execute the next case branch with a break statement to implement the function of ignoring case sensitivity of user console input
case 'M':
System.out.println("Monday");
break; case 't':
//When lowercase letters are entered, use the switch structure feature to execute the next case branch with a break statement to implement the function of ignoring case sensitivity of user console input
case 'T':
System.out.print("Since Tuesday (Tuesday) and Thursday (Thursday) both start with the letter T, you need to enter the second letter to correctly judge: ");
letter = input.next();
//Determine whether the length of the user console input string is one letter
if (letter.length() == 1){
//Use the character that takes the first index bit to allow Scanner to receive char type input
weekSecond = letter.charAt(0);
//Use the or (||) operator to implement the function of ignoring case sensitivity of user console input
if (weekSecond == 'U' || weekSecond == 'u'){
System.out.println("Tuesday");
break;
//Use the or (||) operator to implement the function of ignoring case sensitivity of user console input
} else if (weekSecond == 'H' || weekSecond == 'h'){
System.out.println("Thursday");
break;
//Console error message
} else{
System.out.println("Input error, the second letter of the week value cannot be recognized, the program ends!");
break;
}
} else {
//Console error message
System.out.println("Input error, only one letter can be entered, the program ends!");
break;
ca}se 'w':
//When lowercase letters are entered, use the switch structure feature to execute the next case branch with a break statement to implement the function of ignoring case sensitivity of user console input
case 'W':
System.out.println("Wednesday");
break; case 'f':
//When lowercase letters are entered, use the switch structure feature to execute the next case branch with a break statement to implement the function of ignoring case sensitivity of user console input
case 'F':
System.out.println("Friday");
break; case 's':
//When lowercase letters are entered, use the switch structure feature to execute the next case branch with a break statement to implement the function of ignoring case sensitivity of user console input
case 'S':
System.out.print("Since Saturday (Saturday) and Sunday (Sunday) both start with the letter S, you need to enter the second letter to correctly judge: ");
letter = input.next();
//Determine whether the length of the user console input string is one letter
if (letter.length() == 1){
//Use the character that takes the first index bit to allow Scanner to receive char type input
weekSecond = letter.charAt(0);
//Use the or (||) operator to implement the function of ignoring case sensitivity of user console input
if (weekSecond == 'A' || weekSecond == 'a'){
System.out.println("Saturday");
break;
//Use the or (||) operator to implement the function of ignoring case sensitivity of user console input
} else if (weekSecond == 'U' || weekSecond == 'u'){
System.out.println("Sunday");
break;
//Console error message
} else{
System.out.println("Input error, the second letter of the week value cannot be recognized, the program ends!");
break;
}
} else{
//Console error message
System.out.println("Input error, only one letter can be entered, the program ends!");
break;
de}fault:
//Console error message
System.out.println("Input error, the first letter of the week value cannot be recognized, the program ends!");
break;
}
} else{
//Console error message
System.out.println("Input error, only one letter can be entered, the program ends!");
}
}
}
[Program 27] Title: Find prime numbers within 100
public class Ex27 { public static void main(String args[])
{int sum,i; for(sum=2;sum<=100;sum++)
{for(i=2;i<=sum/2;i++)
{if(sum%i==0) break;
}if(i>sum/2)
System.out.println(sum+"is a prime number");
}
}
}
[Program 28] Topic: Sort 10 numbers
1. Program analysis: You can use the selection method, that is, from the last 9 comparison processes, select the smallest one to exchange with the first element. By analogy next time, use the second element to compare with the last 8 elements and exchange them. .
import java.util.Arrays; import java.util.Random; import java.util.Scanner; public class Ex28 { public static void main(String[] args) { int arr[] = new int[11];
Random r=new Random(); for(int i=0;i<10;i++){
arr[i]=r.nextInt(100)+1;//Get 10 integers within 100
}
Arrays.sort for (arr); (int i=0;i<arr.length;i++){
System.out.print(arr[i]+"/t");
}
System.out.print("/nPlease Input a int number: ");
Scanner sc=new Scanner(System.in);
arr[10]=sc.nextInt();//Enter an int value
Aflorrays.sort(arr); (int i=0;i<arr.length;i++){
System.out.print(arr[i]+"/t");
}
}
}
[Program 29] Question: Find the sum of the diagonal elements of a 3*3 matrix
1. Program analysis: Use double for loops to control the input of a two-dimensional array, and then accumulate a[i][i] and output it.
public class Ex29 { public static void main(String[] args){ double sum=0; int array[][]={{1,2,3},{4,5, 6},{7,7,8 }}; for(int i=0;i<3;i++) for(int j=0;j<3;j++){ if(i==j)
sum=sum + array[i][j];
}
System.out.println(sum);
}
}
[Program 30] Question: There is an array that has been sorted. Now enter a number and insert it into the array according to the original rules.
1. Program analysis: First determine whether this number is greater than the last number, and then consider inserting the middle number. After insertion, the numbers after this element will be moved back one position in turn.
import java.util.Random; public class ArraySort { public static void main(String[] args)
{ int temp=0; int myarr[] = new int[12];
Random r=new Random(); for(int i=1;i<=10;i++)
fomryarr[i]=r.nextInt(1000); (int k=1;k<=10;k++)
fSoyrstem.out.print(myarr[k]+","); (int i=1;i<=9;i++) for(int k=i+1;k<=10;k++) if(myarr[i ]>myarr[k])
{
temp=myarr[i];
myarr[i]=myarr[k];
myarr[k]=temp;
}
fSoyrstem.out.println(""); (int k=1;k<=10;k++)
System.out.print(myarr[k]+",");
fmoyarrr[11]=r.nextInt(1000); (int k=1;k<=10;k++) if(myarr[k]>myarr[11])
{
fteomrp=myarr[11]; (int j=11;j>=k+1;j--)
myarr[j]=myarr[j-1];
myarr[k]=temp;
}
forSystem.out.println(""); (int k=1;k<=11;k++)
System.out.print(myarr[k]+",");
}
}
[Program 31] Title: Output an array in reverse order.
Program analysis: Swap the first and last.
In fact, it is simpler to control variables with a loop:
for(int k=11;k>=1;k--)
System.out.print(myarr[k]+",");
[Program 32] Title: Take the 4 to 7 digits of an integer a starting from the right end.
Program analysis: You can think about it this way:
(1) First shift a to the right by 4 bits.
(2) Set a number with the lower 4 bits all being 1 and the rest being all 0. Available~(~0 < <4)
(3) Perform & operation on the above two.
public class Ex32 { public static void main(String[] args)
{ int a=0; long b=18745678;
a=(int) Math.floor(b % Math.pow(10,7)/Math.pow(10, 3));
System.out.println(a);
}}
【Program 33】
Question: Print out Yang Hui’s triangle (required to print out 10 lines as shown below)
1. 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 Ex33 { public static void main(String args[]){ int i,j; int a[][];
a=new int[8][8]; for(i=0;i<8;i++){
a[i][i]=1;
a[i][0]=1;
for}(i=2;i<8;i++){ for(j=1;j<=i-1;j++){
a[i][j]=a[i-1][j-1]+a[i-1][j];
}
}for(i=0;i<8;i++){ for(j=0;j<i;j++){
System.out.printf(" "+a[i][j]);
}
System.out.println();
}
}
}
[Program 34] Question: Input 3 numbers a, b, c, and output them in order of size.
1. Program analysis: using pointer methods.
public class Ex34 { public static void main(String[] args)
{int []arrays = {800,56,500}; for(int i=arrays.length;--i>=0;)
{for(int j=0;j<i;j++)
{if(arrays[j]>arrays[j+1])
{int temp=arrays[j];
arrays[j]=arrays[j+1];
arrays[j+1]=temp;
}}} for(int n=0;n<arrays.length;n++)
System.out.println(arrays[n]);
}
}
[Program 35] Title: Input an array, exchange the largest element with the first element, exchange the smallest element with the last element, and output the array.
import java.util.*; public class Ex35 { public static void main(String[] args) { int i, min, max, n, temp1, temp2; int a[];
System.out.println("Input the length of the array:");
Scanner keyboard = new Scanner(System.in);
n = keyboard.nextInt();
a = new int[n]; for (i = 0; i < n; i++) {
System.out.print("Enter the "th" + (i + 1) + "data");
a[i] = keyboard.nextInt();
}
//The above is the input of the entire array
max = 0;
min = 0;
//Set two flags, starting with both pointing to the first number
for (i = 1; i < n; i++) { if (a[i] > a[max])
max = i; //Traverse the array, if it is greater than a[max], assign his array subscript to max
if (a[i] < a[min])
min = i; //Same as above, if it is less than a[min], assign his array subscript to min
}
//The above for loop finds the maximum and minimum values, max is the subscript of the maximum value, min is the subscript of the minimum value
temp1 = a[0];
temp2 = a[min]; //These two temps are only for use in exchange
a[0] = a[max];
a[max] = temp1; //First exchange a[0] and the maximum value a[max]
if (min != 0) { //If the minimum value is not a[0], execute the following
a[min] = a[n - 1];
a[n - 1] = temp2; //Exchange a[min] and a[n-1]
} else { //If the minimum value is a[0], execute the following
a[max] = a[n - 1];
a[n - 1] = temp1;
}
for (i = 0; i < n; i++) { //Output array
System.out.print(a[i] + " ");
}}}
[Program 36] Question: There are n integers, so that the previous numbers are moved backward by m positions, and the last m numbers become the first m numbers [Program 37]
Question: There are n people sitting in a circle and numbering them in order. Start counting from the first person (counting from 1 to 3). Anyone who reports 3 exits the circle and asks what is the original number of the person left at the end.
import java.util.Scanner; public class Ex37 { public static void main(String[] args) {
Scanner s = new Scanner(System.in); int n = s.nextInt(); boolean[] arr = new boolean[n]; for(int i=0; i<arr.length; i++) {
arr[i] = true;//When the subscript is TRUE, it means it is still in the circle
}int leftCount = n; int countNum = 0; int index = 0; while(leftCount > 1) {
if(arr[index] == true) {//When in the circle
countNum ++; //count increment
if(countNum == 3) {//When reporting 3
countNum =0;//Continue counting from zero
arr[index] = false;//This person exits the circle
leftCount --;//The remaining number of people is reduced by one
}
}
index ++;//Every time a number is reported, the subscript increases by one
if(index == n) {//It is a circular count. When the subscript is greater than n, it means that one circle has been counted.
index = 0;//Set the index to zero and start again.
}
}for(int i=0; i<n; i++) { if(arr[i] == true) {
System.out.println(i);
}
}
}
}
【Program 38】
Question: Write a function to find the length of a string. Enter the string in the main function and output its length.
import java.util.Scanner; public class Ex38 { public static void main(String [] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Please enter a string");
String mys= s.next();
System.out.println(str_len(mys));
} public static int str_len(String x)
{ return x.length();
}
}
Question: 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
【Program 39】
Topic: String sorting.
import java.util.*; public class test{ public static void main(String[] args)
{
ArrayList<String> list=new ArrayList<String>();
list.add("010101");
list.add("010003");
list.add("010201");
Collections.sort for (list); (int i=0;i<list.size();i++){
System.out.println(list.get(i));
}}}
【Program 40】
Topic: There are a bunch of peaches on the beach, and five monkeys have to divide them. The first monkey divided the pile of peaches into five parts. If there was one more, the monkey threw the extra one into the sea and took away one part. The second monkey divided the remaining peach into five equal parts, and there was one more. It also threw the extra peach into the sea and took one. The third, fourth, and fifth monkeys all did the same. Yes, how many peaches were there on the beach?
public class Dg {
static int ts=0;//Total number of peaches
int fs=1;//Record the number of points
static int hs=5;//number of monkeys...
int tsscope=5000; //The value range of the number of peaches. If it is too large, it will easily overflow.
public int fT(int t){ if(t==tsscope){
//Cancel the recursion when the number of peaches reaches the maximum value range
System.out.println("End");
return 0;
}else{ if((t-1)%hs==0 && fs <=hs){ if(fs==hs)
{
System.out.println("The peach dividing condition is met when the number of peaches = "+ts +"");
}
fs+=1;
return fT((t-1)/5*4);//Return the total amount left after the monkey takes one piece
}else
{
//The conditions are not met
fs=1; //The number of minutes is reset to 1
return fT(ts+=1);//add +1 to the number of peaches
}}}
public static void main(String[] args) { new Dg().fT(0);
}
}