### 1, Fundamentals of Java syntax (III) - Cases

#### 1.1 data exchange procedure

##### 1.1.1 problems:

Realize the data exchange between two variables. For example, there are two integer variables A and b. now it is necessary to exchange the value of variable a and the value of variable b. For example, the original value of a is 100, the original value of b is 200, and after exchange, the value of a is 200 and the value of b is 100.

##### 1.1.2 scheme:

The system uses intermediate variables to solve the above problems.

Step 1: assign the value of variable a to the intermediate variable, and the code is as follows:

int temp=a;

Step 2: assign the value of b variable to a variable, and the code is as follows:

a=b;

Step 3: assign the value of intermediate variable to b variable, and the code is as follows:

b=temp;

Finally, the exchange between the value of a variable and the value of b variable is realized. As shown in the figure:

##### 1.1.3 reference code:

##### 1.1.4 extension

Do not use intermediate variables to realize the data exchange program, that is, to realize the exchange of two variable values. You can first assign the value of a+b to a, then assign the value of a-b to b, and finally assign the value of a-b to A. please see the following code:

public class SwapExt{ public static void main(String[] args){ int a = 100; int b = 200; System.out.println("a="+a+",b="+b); a=a+b; b=a-b; a=a-b; System.out.println("a="+a+",b="+b); } }

#### 1.2 calculate the displacement of the object in free falling motion

##### 1.2.1 problems:

The system uses an interactive way to calculate the position of an object in free fall motion. The user inputs the free fall time t from the console, and the system calculates the free fall displacement of the object after the time t. The calculation results are kept to one decimal place and output to the console. The system interaction process is shown in the figure

Note: the formula of free fall displacement is: s = 1/2 × g × t*t, where:

s (displacement) (m)

t (time) (s)

g (gravitational acceleration) (9.8m/s2)

For example, if the time t received from the console is 10s, then the displacement s=1/2 × nine point eight × ten × 10=490.0

##### 1.2.2 scheme:

The system uses double type to receive the time data t input from the console. Call the nextDouble() method of Scanner to receive the time data entered by the user from the console. The return value of this method is of type double. The code is as follows:

double t=scanner.nextDouble();

The system calculates the displacement value s according to the displacement formula of the free falling body. The type of S is double, and the code is as follows:

double s=0.5*g*t*t;

**In order to keep one decimal place after the decimal point, the system can use the following methods:**

s=Math.round(10*s)/10.0;

Math's round(double s) method is used to realize the calculation of rounding, and the return value is long type data.

It should be noted that the return value of round(double s) is of type long. The result will not be returned until it is divided by the data of type double

The type is automatically converted to double type, so the divisor is double direct 10.0 instead of int direct 10.

##### 1.2.3 reference code:

import java.util.Scanner; public class FreeFall{ public static void main(String[] args){ Scanner scanner = new Scanner(System.in); double g=9.80; System.out.println("Please enter the free fall time (seconds):"); double t=scanner.nextDouble(); double s=0.5*g*t*t; s=Math.round(10*s)/10.0; System.out.println(t+"Seconds later, the object fell freely"+s+"rice"); } }

##### 1.2.4 extension

The user inputs the falling distance (m) of the object from the console, and then calculates the time (s) it takes to fall this distance. The calculation result needs to keep one decimal place and output the result to the console. The system interaction process is shown in the figure:

The system code is implemented as follows:

import java.util.Scanner; public class FreeFallExt{ public static void main(String[] args){ Scanner scanner=new Scanner(System.in); double g=9.80; System.out.println("Please enter the free fall distance (m):"); double s=scanner.nextDouble(); double t=Math.sqrt(2*s/g); t=Math.round(10*t)/10.0; System.out.println("Object falling"+s+"Meters, need"+t+"second"); } }

#### 1.3 repayment calculator of equal principal and interest

##### 1.3.1 problems:

The system uses interactive method to calculate the repayment of equal principal and interest loans. The user inputs the loan principal, monthly loan interest rate and number of repayment years from the console. The system calculates the monthly repayment amount according to the above information. The monthly repayment amount is required to retain two decimal places and output to the console.

Note: repayment formula of equal principal and interest: payment = (p) × r × (1 + r)^m) / ((1 + r)^m - 1)，

Including: p (loan principal) (yuan) r (loan monthly interest rate) m (number of repayment months)

The system interaction process is shown in the figure:

##### 1.3.2 scheme:

**The system uses double type to define loan principal and monthly loan interest rate. The code is as follows:**

double p=scanner.nextDouble()*10000; double r=scanner.nextDouble()/1200;

**The system uses int type to define the number of repayment years, and the code is as follows:**

int m=scanner.nextInt()*12

The system calculates the repayment according to the repayment formula of equal principal and interest, and uses math Pow (double a,double b) calculates the power operation. This method returns the value of the power of b of a, and the code is as follows:

double payment=(p*r*Math.pow((1+r),m))/(Math.pow(1+r,m)-1);

The system uses math The round() method ensures that the repayment amount keeps two decimal places, and the code is as follows:

Math.round(payment*100)/100.0

##### 1.3.3 reference code:

##### 1.3.4 extension

Calculate the repayment of the loan in the form of equal principal. The user inputs the loan principal, monthly interest rate and repayment years from the console. The system calculates the repayment amount of the first month and the second month according to the above information. The monthly repayment amount is required to retain two decimal places and output to the console. The system interaction process is shown in the figure below:

The repayment formula of equal principal is: monthly repayment amount = loan principal / months of loan period + (principal - accumulated amount of returned principal) × Monthly interest rate

For example, if the loan amount (i.e. loan principal) is 300000 yuan, the annual interest rate of the loan is 6.14%, and the number of repayment years is 20 years, the calculation method is as follows:

Monthly principal: 300000 / 240 = 1250

Monthly interest rate: 6.14% / 12

First month Repayment: 1250 + 300000 * 6.14% / 12 = 2785

Repayment in the second month: 1250 + (300000 - 1250) * 6.14% / 12 = 2778.60

Note: the principal 1250 returned in the first month does not need to calculate interest in the second month. The system code is implemented as follows:

import java.util.Scanner; public class MonthlyPaymentExt { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter your loan principal: (10000)"); double p = scanner.nextDouble() * 10000; System.out.println("Please enter the annual interest rate of your loan:(%)"); double r = scanner.nextDouble() / 1200; System.out.println("Please enter your repayment years:"); int m = scanner.nextInt() * 12; scanner.close(); double firstPayment = p / m + p * r; firstPayment = Math.round(firstPayment * 100) / 100.0; System.out.println("Your repayment amount in the first month is:￥"+ firstPayment); double secondPayment=p/m+(p-p/m)*r; secondPayment=Math.round(secondPayment*100)/100.0; System.out.println("Your repayment amount for the second month is:￥"+ secondPayment); } }

#### 1.4 calculate the distance from Altair to Vega

##### 1.4.1 problems:

Calculate the distance from Altair to Vega. The distance between Altair and Vega is 16.4 light-years. If a magpie is 0.46 meters long, calculate how many magpies the Altair and Vega really need to meet. The console output information is shown in the figure:

Note:

Speed of light: 299792458 M / S

1 light year = (1 * 365 * 24 * 60 * 60 * speed of light / 1000) km

1km = 1km

##### 1.4.2 scheme:

Use double type to define light year variable and magpie length variable. The code is as follows:

double dLightYear=16.4; double dMagpie=0.46;

The int type is used to define the speed of light variable, which does not exceed the maximum value of int, so the int type is used to define the speed of light variable, and the code is as follows:

int speedOfLight=299792458;

Calculate the distance from Altair to Vega according to the formula, and use the long type to define the distance variable from Altair to Vega. The code is as follows:

long d=(long)(dLightYear*365*24*60*60*speedOfLight/1000);

According to the formula, the number of magpies needed to meet the Cowherd and Weaver Girl and build the magpie bridge exceeds the maximum value of int type, but is less than the maximum value of long. Therefore, use long type to define the variable of the number of magpies needed, and the code is as follows:

long numberOfMagpie=(long)(d*1000/dMagpie)

##### 1.4.3 reference code:

The system code is implemented as follows:

##### 1.4.4 extension:

It is said that a person's total path in his life can circle the earth 75 times. The average radius of the earth is 6371.004 kilometers, and the step length of a person's step is about 60 cm. Please calculate how many steps a person has to take in his life? The system interaction process is shown in the figure.

**The system code is implemented as follows:**

#### 1.5 leap year judgment procedure

##### 1.5.1 problems:

Judge whether a year is a leap year. Judge whether the year is a leap year according to the year value entered by the user on the console. The system interaction is shown in the figure:

##### 1.5.2 scheme:

Use the mathematical operator remainder operation (%), the relational operator equal to (= =) and not equal to (! =), the logical operator logical and (& &) and logical or (|) to judge whether a year is a leap year. The judgment result is the value of boolean type. If it is a leap year, the value of boolean type is true, otherwise it is false, and the code is as follows:

boolean isLeapYear=(year%4==0&&year%100!=0)||year%400==0;

Use the ternary operator to obtain the String type information of whether it is a leap year and output it to the console. The code is as follows:

String msg=isLeapYear?year+"It's a leap year":year+"Not a leap year";

##### 1.5.3 reference code:

##### 1.5.4 extension:

Calculate the number of days in a month of a year. The user inputs the year and month values in the console, then calculates the days of the month in the year, and outputs them in the console. The system interaction is shown in the figure:

Note: the big month has 31 days, the small month has 30 days, the February of leap year has 29 days, and the February of non leap year has 28 days. The system code is implemented as follows:

import java.util.Scanner; public class LeapYear{ public static void main(String[]args){ Scanner scanner=new Scanner(System.in); System.out.println("Please enter the year (e.g. 2020)"); int year=scanner.nextInt(); System.out.println("Please enter the month (for example: 1)"); int month=scanner.nextInt(); scanner.close(); //Determine whether it is a leap year boolean isLeapYear=(year%4==0&&year%100!=0)||year%400==0; //Judge the big month and the small month, except February boolean isLittleMonth=month==4||month==6||month==9||month==11; boolean isLargeMonth=month==1||month==3||month==5||month==7||month==8||month==10||month==12; //Calculation days int days=isLittleMonth?30:(isLargeMonth?31: (isLeapYear?29:28)); //output System.out.println(year+"year"+month+"Yue you"+days+"day"); } }

#### 1.6 number sorter

##### 1.6.1 problems:

The system uses an interactive way to sort the three numbers. For example, the original value of three integers a, b, c and a input by the user is 20, the original value of b is 5, and the original value of c is 10. After sorting, the value of a is 5, the value of b is 10, and the value of c is 20. The system interaction is shown in the figure:

##### Scheme 1.2:

The system uses the if statement to sort the three numbers. First, judge the size of a and b and exchange them. The code is as follows:

Secondly, judge the size of a and c and exchange them. The code is as follows:

Finally, judge the size of b and c and exchange them. The code is as follows:

##### 1.6.3 reference code:

import java.util.Scanner; public class MaxofThree { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner=new Scanner(System.in); System.out.println("Please enter three integers in sequence: a，b，c((separated by spaces)"); int a=scanner.nextInt(); int b=scanner.nextInt(); int c=scanner.nextInt(); scanner.close(); System.out.println("a="+a+",b="+b+",c="+c); int temp=0; if(a>b) { temp = a; a = b; b = temp; } if(a>c) { temp = a; a = c; c = temp; } if(b>c) { temp = b; b = c; c = temp; } System.out.println("a="+a+",b="+b+",c="+c); } }

##### 1.6.4 expansion

The user inputs three values on the console, and needs to find out the minimum value of these three values. It is required to use the if statement. The system interaction information is shown in the figure:

import java.util.Scanner; public class MinofThree { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("Please enter three integers in sequence: a，b，c((separated by spaces)"); int a=scanner.nextInt(); int b=scanner.nextInt(); int c=scanner.nextInt(); scanner.close(); int temp = a; if(temp>b) { temp = b; } if(temp>c) { temp = c; } System.out.println("The minimum value is:"+temp); } }

#### 1.7 personal income tax calculator

##### 1.7.1 problems:

Calculate the payment of individual income tax. The user inputs the amount of pre tax salary from the console, and the system calculates the tax payable according to the salary amount entered by the user, as shown in the figure:

Note:

The calculation formula of individual wage tax is:

Tax payable = (salary income - deduction) × Applicable tax rate - quick calculation deduction

Monthly taxable income = monthly salary income - deduction

From September 1, 2011, the progressive tax rate of level 7 excess will be implemented: the deduction is 3500 yuan.

##### 1.7.2 reference code:

package day03; import java.util.Scanner; public class IncomeTax { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter the pre tax amount of your salary(￥):"); double salary = scanner.nextDouble(); double tax = 0.0; double taxIncome = salary-3500; if(taxIncome<=0) { tax = 0.0; }else if(taxIncome<=1500) { tax = taxIncome*0.03; }else if(taxIncome<=4500) { tax = taxIncome*0.10-105; }else if(taxIncome<=9000) { tax = taxIncome*0.20-555; }else if(taxIncome<=35000) { tax = taxIncome*0.25-1005; }else if(taxIncome<=55000) { tax = taxIncome*0.30-2755; }else if(taxIncome<=80000) { tax = taxIncome*0.35-5505; }else { tax=taxIncome*0.45-13505; } System.out.println("The personal income tax you should pay is:￥"+tax); scanner.close(); } }

##### 1.7.3 extension:

Calculate the insurance payment of individual wage income and individual income tax. The user inputs the amount of pre tax salary from the console. The system calculates the total amount of various insurances that should be paid and the tax that should be paid according to the salary amount entered by the user. The system interaction process is shown in the figure:

Note:

The calculation formula of individual wage tax is:

Tax payable = (salary income - insurance amount - deduction) × Applicable tax rate - quick calculation deduction

Monthly taxable income = monthly salary income - insurance amount - deduction

Among them, the payment proportion of each insurance amount is as follows:

Endowment insurance: monthly salary income × 8%

Medical insurance: monthly salary income × 2%

Unemployment insurance: monthly salary income × 0.2%

Provident Fund: monthly salary income × 12%

The system code is implemented as follows:

package day03; import java.util.Scanner; public class InsuranceTax { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("Please enter the pre tax amount of your salary(￥): "); double salary=scanner.nextDouble(); scanner.close(); //Calculate the amount of each insurance double endowmentInsurance=salary*0.08; double medicalInsurance=salary*0.02; double unemploymentInsurance=salary*0.002; double accumulationFund=salary*0.12; double insurance=endowmentInsurance+medicalInsurance+unemploymentInsurance+accumulationFund; System.out.println("The total amount of each insurance you should pay is:￥"+insurance); //Calculate individual income tax double tax=0.0; double taxIncome=salary-insurance-3500; if(taxIncome<=0) { tax = 0.0; }else if(taxIncome<=1500) { tax = taxIncome*0.03; }else if(taxIncome<=4500) { tax = taxIncome*0.10-105; }else if(taxIncome<=9000) { tax = taxIncome*0.20-555; }else if(taxIncome<=35000) { tax = taxIncome*0.25-1005; }else if(taxIncome<=55000) { tax = taxIncome*0.30-2755; }else if(taxIncome<=80000) { tax = taxIncome*0.35-5505; }else { tax=taxIncome*0.45-13505; } System.out.println("The personal income tax you should pay is:￥"+tax); scanner.close(); } }