java process control
1, Scanner object
Basic grammar
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
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()){ //Receive in next mode //Enter hello world String str = scanner.next(); //Output hello System.out.println("The output contents are:"+str); } //All classes belonging to IO streams will always occupy resources if they are not closed scanner.close(); }
public static void main(String[] args) { //Receive data from keyboard Scanner scanner = new Scanner(System.in); System.out.println("Please enter"); String str = scanner.nextLine(); System.out.println("content"+str); scanner.close(); }
What is the difference between next() and nextLine()
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.
- 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.
2, Scanner advanced
Int type
//Create a swept object //An object used to receive user input Scanner scanner = new Scanner(System.in); //Receive data from keyboard int i = 0; float f = 0.0f; //Input prompt System.out.println("please enter an integer"); //judge if (scanner.hasNextInt()){ i = scanner.nextInt(); System.out.println("Integer is" + i); }else { System.out.println("The input is not an integer"); } }
float type
System.out.println("Please enter decimal"); if (scanner.hasNextFloat()){ f = scanner.nextFloat(); System.out.println("Decimal data"+ f); }else { System.out.println("The input is not decimal data"); } //close scanner.close();
3, Sequential structure
4, Select structure
Single selection structure
if(Boolean expression) { //The statement that will be executed if the Boolean expression is true }
public static void main(String[] args) { //equals yi ku si //Single branch structure Scanner scanner = new Scanner(System.in); String s = scanner.nextLine(); if (s.equals("hello")){ System.out.println("Correct input"); } System.out.println("Single branch structure"); scanner.close(); }
Double selection structure
If statement can be followed by else statement. When the Boolean expression value of if statement is false, else statement block will be executed.
if(Boolean expression){ //If the Boolean expression has a value of true }else{ //If the value of the Boolean expression is false }
public static void main(String[] args) { //Pass the examination with a score greater than 60 and fail the examination with a score less than 60 Scanner scanner = new Scanner(System.in); System.out.println("Please enter your score"); double x = scanner.nextDouble(); if (x >= 60){ System.out.println("pass"); }else { System.out.println("Fail, keep trying"); } scanner.close(); }
Multiple selection structure
An IF statement can be followed by an else if... Else statement, which can detect a variety of possible situations.
When using if, else, if and else statements, you should pay attention to the following points:
- 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.
if(Boolean expression 1){ //If the value of Boolean expression 1 is true, execute the code }else if(Boolean expression 2){ //If the value of Boolean expression 2 is true, execute the code }else if(Boolean expression 3){ //If the value of Boolean expression 3 is true, execute the code }else { //If none of the above Boolean expressions is true, execute the code }
public static void main(String[] args) { //Pass the examination with a score greater than 60 and fail the examination with a score less than 60 Scanner scanner = new Scanner(System.in); System.out.println("Please enter your score"); double x = scanner.nextDouble(); if (x >= 60){ System.out.println("pass"); }else if (x >= 30&&x<=50){ System.out.println("Fail, keep trying"); } scanner.close(); }
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.
if(Boolean expression 1){ If the value of Boolean expression 1 is true Execute code if(Boolean expression 2){ If the value of Boolean expression 2 is true Execute code } }
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.
switch(expression){ case value : //sentence break; //Optional case value : //sentence break; //Optional //You can have any number of case statements default : //Optional //sentence }
Switchch case statement rules
- The variable types in the switch statement can be byte, short, int and string
- You can have multiple case statements in a switch statement. Each case is followed by a colon and a value to compare
- When the value of the variable is equal to the value of the case statement, the statement after the case statement starts to execute, and the switch statement will not jump out until the break statement appears.
- A switch statement can contain a default branch, which is generally the last branch of the switch statement (it can be anywhere, but it is recommended to be the last). Default is executed when the value of no case statement is equal to the value of a variable. The default branch does not require a break statement.
public static void main(String[] args) { //Create scanner object Scanner scanner = new Scanner(System.in); //char grade = 'c'; System.out.println("Please enter grade"); while(scanner.hasNextLine()){ String grade = scanner.nextLine(); switch(grade){ case "a": System.out.println("excellent"); break; case "c": System.out.println("good"); break; default: System.out.println("error"); } } }
5, Cyclic structure
while Loop
while 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.
public static void main(String[] args) { //Output 1.... one hundred int i = 1; while (i<=100){ System.out.println(i); i++; } }
public static void main(String[] args) { //Calculation 1.... Sum of 100 int sum = 0; int i = 1; while(i<=100){ sum+=i; i++; } System.out.println(sum); }
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.
public static void main(String[] args) { //View while and do... The difference between while //while first judge whether it is executing //do. . . while executes the judgment first int i = 0; while(i<0){ System.out.println("while"); } System.out.println("*************************"); do { System.out.println("do.....while"); }while (i<0); } /* result: * ************************* do.....while */
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.
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 }
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.
public static void main(String[] args) { //Calculates odd and even sums between 0 and 100 //even numbers int a = 0; //Odd number int b = 0; for (int i = 0; i <= 100; i++) { if (i%2==0){ a+=i; }else { b+=i; } } System.out.println("even numbers"+a); System.out.println("Odd number"+b); }
public static void main(String[] args) { //Calculate the number divided by 5 between 1 and 1000, and output 3 per line for (int i = 1; i < 1000; i++) { if (i%5==0){ System.out.print(i+"\t"); } if (i%15==0){ System.out.println(); } } }
public static void main(String[] args) { //multiplication table /* process */ for (int i = 1; i <= 9; i++) { for (int j = 1; j <= i; j++){ System.out.print(j+"*"+i+"="+i*j+"\t"); } System.out.println(); } }
for loop advanced
Java 5 introduces an enhanced for loop that is mainly used for arrays.
The Java enhanced for loop 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.
public static void main(String[] args) { //Print array //Define an array int[] numbers = {10,20,40,50,60}; //Print it out in the ordinary way for (int i = 0; i < 5; i++) { System.out.println(numbers[i]); } System.out.println("*********************************"); //Traversal array for (int x:numbers){ System.out.println(x); } }
break keyword
break is mainly used in loop statements or switch statements to jump out of the whole statement block.
break jumps out of the innermost loop and continues to execute the following statements of the loop.
continue keyword
continue applies to any loop control structure. The function is to make the program jump to the iteration of the next loop immediately.
In the for loop, the continue statement causes the program to immediately jump to the update statement.
In the while or do... While loop, the program immediately jumps to the judgment statement of Boolean expression.
Application of for loop
Print triangles
public static void main(String[] args) { //Print triangles for (int i = 1; i <= 5; i++) { for (int j = 5; j >= i; j--){ System.out.print("-"); } for (int j = 1; j <= i; j++){ System.out.print("*"); } for (int j = 1; j < i; j++){ System.out.print("*"); } System.out.println(); } }