Zero. Learning objectives of this lecture
- Master addition operator
- Master subtraction operators
- Master multiplication operators
- Master division operator
- Master self increasing and self decreasing operators
1, Operator overview
- An operator is a symbol specifically used to tell a program to perform a specific operation or logical operation. An expression is an expression that consists of constants, variables, and operators. To write a program to process data, in fact, processing is to perform various operations on data. Understanding operators and expressions is the basic work of our program. The lecture notes explain the usage of various operators and precautions for correctly writing Java expressions through cases.
2, Arithmetic Operator
- The arithmetic operator in Java is the symbol used to process four operations, and it is also the simplest and most commonly used operation symbol.
(1) Classification description table
operator | operation | example | result |
---|---|---|---|
+ | Plus sign | +3 | 3 |
- | minus sign | b = 4; -b; | -4 |
+ | plus | 5 + 5 | 10 |
- | reduce | 6 - 4 | 2 |
* | ride | 3 * 4 | 12 |
/ | Division (the result of an integral division in arithmetic) | 32 / 5 | 6 |
% | Modulo (i.e. remainder in arithmetic) | 32 % 5 | 2 |
++ | Self increasing (front) | a = 2; b = ++a; | a = 3; b = 3; |
++ | Self increasing (later) | a = 2; b = a++; | a = 3; b = 2; |
– | Self subtraction (front) | a = 2; b = --a; | a = 1; b = 1; |
– | Self subtraction (after) | a = 2; b = a–; | a = 1; b = 2; |
(2) Precautions
- In the operation of self increment (+ +) and self subtraction (–), if the operator (+ + or –) is placed in front of the operand, the operation of self increment or self subtraction is performed first, and then other operations are performed. On the contrary, if the operator is placed after the operand, other operations will be performed first, and then self increasing or self decreasing operations will be performed.
- In the division operation, when both the divisor and the dividend are integers, the result is also an integer; If the division operation involves decimals, the result will be a decimal.
- When the module (%) operation is performed, the positive and negative of the operation result depends on the sign of the module (% the number on the left) and has nothing to do with the sign of the module (% the number on the right).
- Priority operation, (negative attention) ⟹ \Longrightarrow ⟹*,/,% ⟹ \Longrightarrow ⟹+,-. If you want to change the operation order, you need to add parentheses.
(3) Case demonstration
Task 1. Calculate the score difference and average score
Input the scores of STB, SQL and JAVA of the three subjects, and calculate the score difference between SQL and JAVA and the average score of the three subjects.
- A program consists of four parts: declaration part, input part, processing part and output part. Among them, the processing part is the core of a program, which involves the methods and steps of solving problems, that is, algorithms. Operators, expressions and control structures will be used in the processing part.
- To input various types of data, you need to instantiate the Scanner class and pass a parameter system In (standard byte input stream - Keyboard).
package net.hw.lesson05; import java.util.Scanner; /** * Function: calculate the score difference and average score * Author: Hua Wei * Date: March 4, 2020 */ public class Example501 { public static void main(String[] args) { // Declaration part double stb, java, sql, difference, average; Scanner sc = new Scanner(System.in); // Input part System.out.print("input STB Achievements:"); stb = sc.nextDouble(); System.out.print("input Java Achievements:"); java = sc.nextDouble(); System.out.print("input SQL Achievements:"); sql = sc.nextDouble(); // processing section difference = java - sql; average = (stb + java + sql) / 3; // Output part System.out.println("=========================="); System.out.println("STB\t\tJava\t\tSQL"); System.out.println(stb + "\t" + java + "\t\t" + sql); System.out.println("=========================="); System.out.println("Java And SQL Poor performance:" + difference); System.out.println("Average score of three courses:" + average); } }
Run the program and the results are as follows:
Thinking: how to set the decimal places of the average score? (for example, keep it to two decimal places.)
See Java lecture notes 04: variables and constants The case program in Example409.
The tab escape character \ t is used to control the interval of output items. In the end, each column may not occupy the same width. How can we ensure that each column occupies the same width and is aligned to the left? Very simple, using string The format () method can handle it.
package net.hw.lesson05; import java.util.Scanner; /** * Function: calculate the score difference and average score * Author: Hua Wei * Date: March 4, 2020 */ public class Example501_ { public static void main(String[] args) { // Declaration part double stb, java, sql, difference, average; Scanner sc = new Scanner(System.in); // Input part System.out.print("input STB Achievements:"); stb = sc.nextDouble(); System.out.print("input Java Achievements:"); java = sc.nextDouble(); System.out.print("input SQL Achievements:"); sql = sc.nextDouble(); // processing section difference = java - sql; average = (stb + java + sql) / 3; // Output part System.out.println("======================="); System.out.println(String.format("%-9s%-9s%-9s","STB", "Java", "SQL")); System.out.println(String.format("%-9.1f%-9.1f%-9.1f", stb, java, sql)); System.out.println("======================="); System.out.println("Java And SQL Poor performance:" + difference); System.out.println("Average score of three courses:" + String.format("%.2f", average)); } }
Run the program to view the results:
Description: string format("%-9s%-9s%-9s","STB", "Java", "SQL")
- %-9s -- output string data, with a width of 9. If it is insufficient, fill in the space on the right to produce the left alignment effect; If the actual number of bits of data exceeds the specified number of bits, it shall be output according to the actual number of bits
- %9s -- output string data, with a width of 9. If it is insufficient, fill the space on the left to produce the right alignment effect; If the actual number of bits of data exceeds the specified number of bits, it shall be output according to the actual number of bits
- If you want to output integer data, use% d. of course, you can also specify the width and alignment, such as% 8d and% - 8d (the total number of bits is 8. If the actual number of bits of output data exceeds the specified number, output it according to the actual number of bits, and fill in spaces if it is insufficient)
- If you want to output floating-point data, use% F. of course, you can also specify the width and alignment, such as% 9.1f and% - 9.1f (the total number of digits is 9 and one decimal place is reserved)
Class exercise: programming division with remainder.
Task 2. Print shopping tickets
Print the shopping ticket and calculate the shopping points. Print the shopping ticket at the time of settlement, calculate the shopping points, buy three kinds of goods, and have discounts, payment and change tickets.
package net.hw.lesson05; import java.util.Scanner; /** * Function: print shopping receipts during settlement and calculate the shopping points * Buy three kinds of goods with discount, payment and change * Author: Wei Hua * Date: March 4, 2020 */ public class Example502 { public static void main(String[] args) { // Unit price of three commodities double price1, price2, price3; // Purchase quantity of three commodities int amount1, amount2, amount3; // Shopping discount double discount = 0.8; // Total shopping amount double money; // Actual payment double pay; // Change should be made double change; // Shopping points int points; // Scanner Scanner sc = new Scanner(System.in); // Input part System.out.print("input T Unit price of shirt:"); price1 = sc.nextDouble(); System.out.print("input T Number of T-shirts purchased:"); amount1 = sc.nextInt(); System.out.print("Enter the unit price of tennis shoes:"); price2 = sc.nextDouble(); System.out.print("Enter the number of tennis shoes purchased:"); amount2 = sc.nextInt(); System.out.print("Enter the unit price of tennis rackets:"); price3 = sc.nextDouble(); System.out.print("Enter the number of tennis rackets purchased:"); amount3 = sc.nextInt(); System.out.print("Actual fees paid by customers:"); pay = sc.nextDouble(); // processing section money = (price1 * amount1 + price2 * amount2 + price3 * amount3) * discount; // Calculate total shopping amount change = pay - money; // Calculate the change points = (int) (money / 33); // Calculate shopping points // Output part System.out.println("************Consumption list**********"); System.out.println("Purchase items\t\t Unit Price\t number\t amount of money"); System.out.println("T Shirt\t\t\t" + price1 + "\t" + amount1 + "\t\t¥" + price1 * amount1); System.out.println("Tennis shoes\t\t" + price2 + "\t" + amount2 + "\t\t¥" + price2 * amount2); System.out.println("Tennis racket\t\t" + price3 + "\t" + amount3 + "\t\t¥" + price3 * amount3); System.out.println(); System.out.println("Discount?" + (int) (discount * 10) + "fracture"); System.out.println("Total consumption amount:¥" + money); System.out.println("Actual payment:¥" + pay); System.out.println("give change:¥" + change); System.out.println("Points gained in this shopping:" + points); } }
Run the program and the results are as follows:
Task 3. Lucky draw - calculate the lucky number from the card number
Enter the membership card number (4 digits), decompose the numbers, add the numbers to get the lucky numbers, and then use the lucky numbers to draw the lottery. Write a program to get lucky numbers from the card number.
Difficulty: how to split a four digit number?
Ideas for solving problems: for example, n = 3462
3426 = 3 * 1000 + 4 * 100 + 6 *10 + 2
Except for the single digit 2, all other bits can be divided by 10, which means that 2 is the remainder of 3462 divided by 10. How to express it? 3462 % 10 = 2
After the single digit is obtained, we want to remove the single digit and change the four digits into three digits, and then we can use a similar method to get the end number of three digits, which is actually the ten digits of four digits; So how can we get such a three digit number? 3462 / 10 = 346
346 = 3 * 100 + 4 * 10 + 6 how to get the last number? 346 % 10 = 6
Then turn 346 into 34. What do you do? 346 / 10 = 34
34 = 3 * 10 + 4, how to get the last number? 34 % 10 = 4
Then 34 becomes 3. How? 34 / 10 = 3
package net.hw.lesson05; import java.util.Scanner; /** * Function: calculate the lucky number from the membership card number * The lucky number is equal to the sum of the numbers of the membership card number * Author: Wei Hua * Date: March 4, 2020 */ public class Example503 { public static void main(String[] args) { /* Declaration part */ int id; // Membership card number int x1, x2, x3, x4; // Single digit, ten digit, hundred digit, thousand digit int luckyNumber; // Lucky number Scanner sc = new Scanner(System.in); // Scanner object /* Input part */ System.out.print("Enter the membership card number (four digits):"); id = sc.nextInt(); // Receive an integer from the keyboard /* processing section */ x1 = id % 10; // Take single digit x2 = id / 10 % 10; // Take ten digits x3 = id / 100 % 10; // Take hundreds x4 = id / 1000; // Take thousands luckyNumber = x1 + x2 + x3 + x4; // Calculate lucky numbers /* Output part */ System.out.println("Your lucky number:" + luckyNumber); } }
Thinking question: what happens to the program if the input card number is not four digits? How can this program be improved to only handle the input of four digits? Can our method of splitting numbers be extended to any number of digits?
Task 4. Demonstrate self increasing and self decreasing operations
- There are two cases of self increment: pre self increment and post self increment. Pre auto increase, + A, add first and then use; After self increase, a + +, use first and then increase.
- There are two cases of self subtraction: pre self subtraction and post self subtraction. Front self subtraction, – a, subtraction before use; After self subtraction, a –, use first and then subtract.
Class exercise: give the execution results of the following code.
public class Example503__ { public static void main(String[] args) { int a = 10, b = 20, c, d; c = a++ + b--; d = ++a + --b; System.out.println("c = " + c); System.out.println("d = " + d); } }
Self addition and self subtraction operations are mainly used in the update conditions of circular structure. Please refer to the case of circular structure in the next lecture.