Java foundation and Java process control
User interaction Scanner
Basic syntax: Scanner s = new Scanner(System.in)
Get the input string through the next() and nextLine() methods of the Scanner class. Before reading, we generally need to use hasNext() and hasNextLine() to judge whether there is still input data.
The Scanner object has two methods: next() and nextLine(). The difference is:
- next():
1. Be sure to read valid characters before you can end the input.
2. The next() method will automatically remove the whitespace encountered before entering valid characters.
3. Only after entering a valid character will the blank space entered after it be used as a separator or terminator.
4. next() cannot get a string with spaces. - nextLine():
1. Take Enter as the ending character, that is, the nextLine() method returns all characters before entering carriage return.
2. You can get blank.
For example:
public class Demo01 { public static void main(String[] args) { //Create a scanner object to receive keyboard data Scanner scanner = new Scanner(System.in); System.out.println("use next Reception mode:"); //Judge whether the user has entered a string if(scanner.hasNext()){ String str = scanner.next(); System.out.println("The input content is" + str); } //If the IO stream is not closed, it will always occupy resources. Develop a good habit of turning it off when it is used up scanner.close(); } }
When running and entering "hello world", the result is:
And:
public class Demo02 { public static void main(String[] args) { //Create a scanner object to receive keyboard data Scanner scanner = new Scanner(System.in); System.out.println("use nextLine Reception mode:"); //Judge whether the user has entered a string if(scanner.hasNextLine()){ String str = scanner.nextLine(); System.out.println("The input content is" + str); } //If you don't close the IO stream, it will always occupy resources. Make a good habit of turning it off when it's used up scanner.close(); } }
When you run and enter "hello world", the result is:
Sequential structure
- The basic structure of Java is a sequential structure. Unless otherwise specified, it will be executed sentence by sentence in order
- Sequential structure is the simplest algorithm structure
- Statement to statement and box to box are carried out from top to bottom. It is composed of several processing steps executed in turn. It is a basic algorithm structure that any algorithm is inseparable from
public class ShunxuDemo { public static void main(String[] args) { System.out.println("hello1"); System.out.println("hello2"); System.out.println("hello3"); System.out.println("hello4"); } }
Select structure
if single selection structure
We often need to judge whether something is feasible before we execute it. Such a process is represented by an if statement in the program
- Syntax:
if(Boolean expression) { //The statement that will be executed if the Boolean expression is true }
if double selection structure
If there is a demand now, the company wants to buy a software. If it succeeds, it will pay 1 million yuan to people. If it fails, it will find someone to develop it by itself. Such a requirement cannot be met with an if. We need to have two judgments and a double selection structure, so we have an if else structure.
- Syntax:
if(Boolean expression) { //If the Boolean expression has a value of true }else{ //If the value of the Boolean expression is false }
if multiple selection structure
In reality, there may also be multi-level judgment, such as A score between 90-100 and B ················································································.
- Syntax:
if(Boolean expression 1) { //If the value of Boolean expression 1 is true }else if(Boolean expression 2) { //If the value of Boolean expression 2 is true }else if(Boolean expression 3) { //If the value of Boolean expression 3 is true }else { //If none of the above Boolean expressions is true }
Nested if structure
It is legal to use nested if... Else statements. That is, you can use an if or else if statement in another if or else if statement. You can nest else if... Else like an IF statement.
- Syntax:
if(Boolean expression 1) { //If the value of Boolean expression 1 is true if(Boolean expression 2){ //If the value of Boolean expression 2 is true } }
switch multiple selection structure
- Another implementation of the multiple selection structure is the switch case statement.
- The switch case statement determines whether a variable is equal to a value in a series of values. Each value is called a branch.
- The type variable in the switch statement can be byte, short, int, char or String.
- The case tag must be a string constant or literal.
- Syntax:
switch(expression){ case value: //sentence break;//Optional case value: //sentence break;//Optional //You can use any number of case statements default://Optional //sentence }
Cyclic structure
while Loop
while loop is the most basic loop. Its structure is:
while(Boolean expression){ //Cyclic content }
- As long as the Boolean expression is true, the loop will continue to execute.
- In most cases, we will stop the loop. We need a way to invalidate the expression to end the loop.
- In a few cases, the loop needs to be executed all the time, such as the server's request response listening, etc.
- If the loop condition is always true, it will cause infinite loop [dead loop]. We should try to avoid dead loop in normal business programming. It will affect the program performance or cause the program to get stuck and run away!
do while loop
- For the while statement, if the condition is not met, it cannot enter the loop. But sometimes we need to perform at least once even if the conditions are not met.
- The do... While loop is similar to the while loop, except that the do... While loop is executed at least once.
Its structure is:
do{ //Cyclic content }while(Boolean expression);
Differences between while and do while:
While judges before execution, do while executes before judgment
Do while always ensures that the loop body is executed at least once
for loop
- Although all loop structures can be represented by while or do while, Java provides another statement - for loop, which makes some loop structures simpler.
- for loop statement is a general structure that supports iteration. It is the most effective and flexible loop structure.
- The number of times the for loop is executed is determined before execution. The syntax format is as follows:
for(initialization;Boolean expression;to update){ //Code statement }
explain:
The initialization step is performed first. You can declare a type, initialize one or more loop control variables, or empty statements.
Detect the value of Boolean expression. If it is true, the loop body is executed; If it is false, the loop terminates and starts executing the statements after the loop body.
After executing a loop, update the loop control variable (the iteration factor controls the increase or decrease of the loop variable).
Check the value of the Boolean expression again and loop through the above procedure.
Exercise 1:
Calculates the sum of odd and even numbers between 0 and 100
public class ForDemo02 { public static void main(String[] args) { //Calculates the sum of odd and even numbers between 0 and 100 int oddSum = 0; int evenSum = 0; for (int i = 0;i <= 100;i++){ if(i % 2 != 0){ //Odd number oddSum += i; } else{ //even numbers evenSum += i; } } System.out.println("The sum of odd numbers is" + oddSum); System.out.println("The sum of even numbers is" + evenSum); } }
Exercise 2:
Use the for loop to output the number that can be divided by 5 between 1-100, and output 3 in each line
public class ForDemo03 { public static void main(String[] args) { //Use the for loop to output the number that can be divided by 5 between 1-100, and output 3 in each line for (int i = 1; i <= 1000; i++) { if(i % 5 == 0){//Divided by 5 System.out.print(i + "\t"); } if(i % (5 * 3) == 0){//Each line System.out.println(); } } } }
Exercise 3:
Print 99 multiplication table
public class ForDemo04 { public static void main(String[] args) { for (int j = 1; j <= 9; j++) { for (int i = 1; i <= j; i++) { System.out.print(j + "*" + i + "=" + (j * i) + "\t"); } System.out.println(); } } }
Enhance a simple understanding of the for loop
Syntax format:
for(Declaration statement : expression){ //Code statement }
Declaration statement: declare a new local variable. The type of the variable must match the type of the array element. Its scope is limited to the circular statement block, and its value is equal to the value of the array element at this time.
Expression: an expression is the name of the array to be accessed, or a method whose return value is an array.
For example:
public class ForDemo05 { public static void main(String[] args) { int[] numbers = {10,20,30,40,50};//An array is defined //Traversing the elements of an array for (int x:numbers){//Assign the value of each item of numbers to x System.out.println(x); } } }
break and continue
- Break in the body of any loop statement, you can use break to control the flow of the loop. Break is used to forcibly exit the loop without executing the remaining statements in the loop. (break statements are also used in switch statements)
public class BreakDemo { public static void main(String[] args) { int i = 0; while(i < 100){ i++; System.out.println(i); if (i == 30){ break; } } } }
break just terminates the loop, not the program
public class BreakDemo { public static void main(String[] args) { int i = 0; while(i < 100){ i++; System.out.println(i); if (i == 30){ break; } } System.out.println("Just terminate the loop, not the program"); } }
- The continue statement is used in the body of a loop statement to terminate a loop process, that is, skip the statements that have not been executed in the loop body, and then determine whether to execute the loop next time.
public class ContinueDemo { public static void main(String[] args) { int i = 0; while (i < 100){ i++; if (i % 10 == 0){ System.out.println(); continue; } System.out.print(i); } } }