Scanner object
In Java 5 and later versions, we can use Java util. Scanner to get user input. The basic syntax for creating a scanner object is as follows:
Scanner sc = new Scanner(System.in);
We can 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 determine whether there is any input data.
When using next():
- Be sure to read valid characters before you can end the input.
- The next() method will automatically remove the whitespace encountered before entering valid characters.
- Only after entering a valid character will the blank space entered after it be used as a separator or terminator.
- Cannot get a string with spaces.
Example:
package com.wmwx.Scanner; import java.util.Scanner; public class Demo01 { public static void main(String[] args) { //Create a scanner object to receive data from the keyboard Scanner sc = new Scanner(System.in); System.out.println("Please enter:"); //Judge whether the user has entered a string if (sc.hasNext()){ //Receive in next mode String str = sc.next(); System.out.println("The input content is:"+str); //Enter "hello world" and output "hello" } //All classes belonging to IO streams will always occupy resources if they are not closed //Get into the habit of turning it off when you run out sc.close(); } }
When using nextLine():
- Take Enter as the ending character, that is, the nextLine() method returns all characters before entering carriage return.
- You can get a string with spaces.
Example:
package com.wmwx.Scanner; import java.util.Scanner; public class Demo02 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Please enter:"); if (sc.hasNextLine()){ //Receive using nextLine String str = sc.nextLine(); System.out.println("The input content is:"+str); //Enter "hello world" and output "hello world" } sc.close(); } }
Sequential structure
The basic structure of Java is a sequential structure. Unless otherwise specified, it will be executed sentence by sentence from top to next.
Example:
package com.wmwx.struct; public class Demo01 { public static void main(String[] args) { //Sequential structure, executed from top to bottom System.out.println("1"); System.out.println("2"); System.out.println("3"); System.out.println("4"); System.out.println("1"); } }
Select structure
There are five kinds of selection structures in Java:
- if single selection structure
- if double selection structure
- if multiple selection structure
- Nested if structure
- switch multiple selection structure
if single selection structure
The syntax is as follows:
if (Boolean expression){ //Statement executed when Boolean expression is true }
Example:
package com.wmwx.struct; import java.util.Scanner; public class IfDemo01 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter:"); //Determine whether the content is entered if (scanner.hasNextLine()){ String str = scanner.nextLine(); //Judge whether the input string is equal to "hello" if (str.equals("hello")){ //If equal, output this sentence System.out.println("You entered:"+str); } } scanner.close(); } }
if double selection structure
The syntax is as follows:
if (Boolean expression){ //Statement executed when Boolean expression is true } else { //Statement executed when Boolean expression is false }
Example:
package com.wmwx.struct; import java.util.Scanner; public class IfDemo02 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter your grade:"); int score = scanner.nextInt(); //Judge that if the test score is not less than 60, you will pass, otherwise you will fail if (score>=60){ System.out.println("pass"); }else{ System.out.println("fail,"); } scanner.close(); } }
if multiple selection structure
The syntax is as follows:
if (Boolean expression 1){ //Statement executed when Boolean expression 1 is true } else if (Boolean expression 2){ //Statement executed when Boolean expression 2 is true } else if (Boolean expression 3){ //Statement executed when Boolean expression 3 is true } //... ... else if (Boolean expression n){ //Statement executed when Boolean expression n is true } else { //The statement executed when the above Boolean expressions are false }
be careful:
- An IF statement can have at most one else statement, which follows all else if statements.
- An IF statement can have several else if statements, which must precede the else statement.
- Once one else if statement is detected as true, the other else if and else statements will skip execution.
Example:
package com.wmwx.struct; import java.util.Scanner; public class IfDemo03 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter your grade:"); int score = scanner.nextInt(); //Judge test scores if (score<100 && score>=95){ System.out.println("Credits: 4.5"); }else if (score<95 && score>=90){ System.out.println("Credits: 4.0"); }else if (score<90 && score>=85){ System.out.println("Credits: 3.5"); }else if (score<85 && score>=80){ System.out.println("Credits: 3.0"); }else if (score<80 && score>=75){ System.out.println("Credits: 2.5"); }else if (score<75 && score>=70){ System.out.println("Credits: 2.0"); }else if (score<70 && score>=65){ System.out.println("Credits: 1.5"); }else if (score<65 && score>=60){ System.out.println("Credits: 1.0"); }else if (score<60 && score>=0){ System.out.println("fail,"); }else{ System.out.println("The result is illegal!"); } scanner.close(); } }
Nested if structure
The syntax is as follows:
if (Boolean expression 1){ //Statement executed when Boolean expression 1 is true if (Boolean expression 2){ //Statement executed when Boolean expression 2 is true } }
switch multiple selection structure
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 syntax is as follows:
switch(expression){ case value1 : //Statement executed when expression is equal to value1 break; //Jump out of switch structure case value2 : //Statement executed when expression is equal to value2 break; //... ... case valuen : //Statement executed when expression is equal to value n break; default : //Statement executed when expression is equal to value1 }
Example:
package com.wmwx.struct; public class SwitchDemo01 { public static void main(String[] args) { String grade = "B level"; switch (grade){ case "A level": System.out.println("Excellent!"); break; case "B level": System.out.println("Good!"); break; case "C level": System.out.println("Medium!"); break; case "D level": System.out.println("Pass!"); break; case "E level": System.out.println("fail!"); break; default: System.out.println("Unknown level!"); } } }
Cyclic structure
Sequential program statements can only be executed once. If you want to perform the same operation multiple times, you need to use a loop structure.
There are four loop structures in Java:
- while loop
- do... while loop
- for loop
- Enhanced for loop for arrays
while Loop
while is the most basic loop. Its syntax is:
while( Boolean expression ) { //Cyclic content }
be careful:
- As long as the Boolean expression is true, the loop will continue to execute.
- In most cases, it will stop the loop, and you need a way to invalidate the Boolean 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 and so on.
- Boolean expressions that are always true will cause an endless loop
Example:
package com.wmwx.struct; public class WhileDemo02 { public static void main(String[] args) { //Output 1 ~ 100 and sum them int i = 0; int sum = 0; while (i<100){ i++; sum = sum + i; System.out.println(i); //Output i } System.out.println(sum); //Output sum } }
do...while Loop
The do... While loop is similar to the while loop, except that the do... While loop is executed at least once. For the while statement, if the condition is not met, it cannot enter the loop.
The syntax is as follows:
do { //Code statement }while(Boolean expression);
Example:
package com.wmwx.struct; public class DoWhileDemo01 { public static void main(String[] args) { //Output 1 ~ 100 and sum them int i = 0; int sum = 0; do { i++; sum = sum + i; System.out.println(i); //Output i }while (i<100); System.out.println(sum); //Output sum } }
for loop
The execution times of the for loop are determined before execution, and its syntax format is as follows:
for(initialization; Boolean expression; to update) { //Code statement }
There are the following explanations for the for loop:
- Perform the initialization step first. You can declare a type, but you can initialize one or more loop control variables or empty statements.
- Then, the value of the Boolean expression is detected. If true, the loop body is executed. If false, the loop terminates and starts executing the statement after the loop body.
- After executing a loop, update the loop control variable.
- Detect the Boolean expression again. Loop through the above procedure.
Example:
package com.wmwx.struct; public class ForDemo01 { public static void main(String[] args) { //Calculate the odd sum and even sum within 0 ~ 100 int odd = 0; //Odd number int even = 0; //even numbers for (int i = 1; i <= 100; i++) { if(i%2==0){ //It's an even number even = even + i; }else{ //It's an odd number odd = odd + i; } } System.out.println(odd); //Output 2500 System.out.println(even); //Output 2550 } }
Enhanced for loop
Java 5 introduces an enhanced for loop that is mainly used for arrays. The syntax format is as follows:
for(Declaration statement : expression) { //Code sentence }
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.
Example:
package com.wmwx.struct; public class ForDemo03 { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; //Define an array //Traversing elements in an array for (int x : numbers){ System.out.println(x); } } }