catalogue
if multiple selection structure
switch multiple selection structure
Process control
User interaction Scanner
-
In the basic syntax we learned before, we did not realize the interaction between programs and people, but Java provides us with such a tool class that we can obtain user input.
java.util.Scanner is a new feature of Java 5. We can get user input through scanner class.
-
Basic syntax:
Scanner s =new Scanner(System.in);
-
Get the input string through the next() and nextLine() methods of the Scanner class. We generally need to use hasNext() and hasNextLine() before reading
Determine whether there is any input data
package com.chang.Control; import java.util.Scanner; public class Control0103 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);//Create a scanner object to receive keyboard input data System.out.println("Please enter");//Give you a prompt for the typist String str = scanner.nextLine();//Use the nextLine method to receive input data System.out.println("The you entered is"+str);//output scanner.close();//Close scanner to save resources. } }
next()
-
Be sure to read valid characters before you can end the input
-
The next() method will automatically remove the whitespace encountered by the input valid characters.
-
As long as a valid character is entered, the blank space entered after it will be used as a separator or terminator.
-
next() cannot get a string with spaces
package com.chang.Control; import java.util.Scanner; public class Control01 { public static void main(String[] args) { //Create a scanner object to receive keyboard data Scanner str = new Scanner(System.in); System.out.println("use next input");//Enter Hello World //Judge whether the user has entered a string if(str.hasNext()){ //Receive in next mode String s = str.next(); System.out.println("The you entered is"+s); //The output is Hello, because the next mode takes the blank character as the separator or Terminator! } //All classes belonging to IO streams will always occupy resources if they are not closed. Make a good habit of closing them str.close(); } }
nextLine()
-
Take Enter as the ending character, that is, the nextLine() method returns all characters before entering carriage return
-
Can get blank
package com.chang.Control; import java.util.Scanner; public class Control0102 { public static void main(String[] args) { //Create a scanner object to receive keyboard input data Scanner scanner = new Scanner(System.in); //Prompt for input System.out.println("use nextLine input"); //Judge whether the user has entered a string if (scanner.hasNextLine()){ //Receive using the nextLine() method String str = scanner.nextLine(); //Output user input data System.out.println("The you entered is"+str); } //Close scanner to save resources scanner.close(); } }
hasNextInt() hasNextFloat()
package com.chang.Control; import java.util.Scanner; public class Control02 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int a = 0; float f = 0.0f; System.out.println("please enter an integer"); if(scanner.hasNextInt()){ a = scanner.nextInt(); System.out.println("The number you entered is an integer"+a); }else { System.out.println("The number you entered is not an integer"); } System.out.println("Please enter decimal"); if (scanner.hasNextFloat()){ f = scanner.nextFloat(); System.out.println("The number you entered is decimal"+ f); }else { System.out.println("The number you entered is not a decimal"); } scanner.close(); } }
scanner.hasNextFloat(): judge whether the data entered by the user is of type foat. If it is true, if it is not, it will return false. However, another problem needs to be considered. For the basic data type in java, int is smaller than float. When the user enters data of type int, it passes the scanner The judgment of hasnextfloat() is true, so the int type will be automatically converted to float type
hasNextDouble()
package com.chang.Control; import java.util.Scanner; public class Control0202 { //We can input multiple numbers and find their sum and average. For each number, press enter to confirm the person. Enter a non number to end the input and output the execution result public static void main(String[] args) { Scanner scanner = new Scanner(System.in); //and double sum = 0; //Several numbers were entered in the calculation int m = 0; System.out.println("Please enter"); //Determine whether there is any input through the whlie loop, and sum and count each input in it while (scanner.hasNextDouble()){ double a = scanner.nextDouble(); m++; sum = sum+a; System.out.println("This is the second input"+m+"Number,Their sum is"+sum); } System.out.println("The sum is"+sum); System.out.println("The average is"+(sum/m)); scanner.close(); } }
Sequential structure
-
The basic structure of Java is sequential structure. Unless otherwise specified, it will be executed sentence by sentence in order.
-
Sequential structure is the simplest algorithm structure
----> A -----> B --------->
-
Between statements and between boxes, it is carried out from top to bottom, which is composed of several processing steps executed in turn,
It is a basic algorithm structure that any algorithm is inseparable from.
```java package com.chang.Control; public class Control03 { //Sequential structure 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
}
package com.chang.Control; import java.util.Scanner; public class Control04 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter"); String str = scanner.nextLine(); // equals: determines whether the input string is equivalent to the compared string //Contains: interpret whether the input string contains a comparison string if(str.equals("Hello")){ System.out.println("You lost right"); } System.out.println("You have entered the wrong number"); scanner.close(); } }
if double selection structure
-
Now there is a demand. The company wants to buy a software. If it succeeds, it will pay 100w yuan to people; Failed, find someone to develop it yourself.
Such a requirement cannot be solved with one if. We need to have two judgments and a double selection structure, so there is
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
}
package com.chang.Control; import java.util.Scanner; public class Control0402 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter your grade"); int score = scanner.nextInt(); if(score>=60){ System.out.println("pass"); }else{ System.out.println("fail,"); } scanner.close(); } }
if multiple selection structure
-
We found that the code just now does not conform to the actual situation. The real situation is good. There may be ABCD and interval multi-level judgment.
For example, 90-100 is A, 80-90 is B Wait, in life, we often have more than two choices, so we
A multi choice structure is needed to solve this kind of problem
-
Syntax:
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 1 is true, execute the code }else if(Boolean expression 3){ //If the value of Boolean expression 1 is true, execute the code }else{ //If none of the above Boolean expressions is true, execute the code }
package com.chang.Control; import java.util.Scanner; public class Control0403 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); /* if There is at most one else statement in the statement, and the statement is followed by all else if statements if A statement can have several else if statements, which must precede the else statement. Once one else if statement is detected as true, other else if statements and soybean milk skip execution. */ System.out.println("Please enter your grade"); int score = scanner.nextInt(); if(score==100){ System.out.println("Full mark"); }else if(score>=90 && score<100){ System.out.println("A level"); }else if(score>=80 && score<90){ System.out.println("B level"); }else if(score>=70 && score<80){ System.out.println("C level"); }else if(score>60 && score<70){ System.out.println("D level"); }else if(score<60){ System.out.println("fail,"); }else { System.out.println("The result is illegal"); } scanner.close(); } }
Nested if structure
-
Use nested if Else statement is legal. That is, you can use if or else in another if or else if statement
Else if statement. You can nest else if like an IF statement else.
-
grammar
if(Boolean expression 1){ //If the value of Boolean expression 1 is true, execute the code if(Boolean expression 2){ //If the value of Boolean expression 2 is true, execute the code } }
-
reflection? We need to find a number between 1 and 100.
if is convenient to judge the interval, and switch matches a specific value
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 variable types in the switch statement can be:
-
byte, short, int, or char.
-
Starting with Java SE 7
-
switch supports String type
-
At the same time, the case tag must be a string constant or literal
-
-
Syntax:
switch(expression){ case value: //sentence break; case value: //sentence break; //There can be any number of statements default: //sentence }
package com.chang.Control; public class Control0501 { public static void main(String[] args) { // Case is penetrating. When there is no break end statement in each case, it will execute the output code in the whole code once // switch matches a specific value; //if judgment interval is convenient char grade = 'A'; switch (grade){ case 'A' : System.out.println("excellent"); break; case 'B': System.out.println("good"); break; case 'C': System.out.println("pass"); break; case 'D': System.out.println("make persistent efforts"); break; case 'E': System.out.println("expel"); break; default: System.out.println("Unknown score"); } } }
package com.chang.Control; public class Control0502 { public static void main(String[] args) { //JDK7's new feature, the expression result can be character creation //String is essentially a number //Decompile with //Decompile Java -- > class (bytecode file) -- decompile (IDEA): File -- > project structure -- > project compiler output---- //--->Right click the file - > open with IDEA String name = "Happy journey"; switch(name){ case "Golden Leaf" : System.out.println("Golden Leaf"); break; case "Happy journey" : System.out.println("Happy journey"); break; case "Yellow Crane Tower" : System.out.println("Yellow Crane Tower"); break; default: System.out.println("Nothing"); } } }
Cyclic structure
-
while loop
-
do while loop
-
for loop
-
In Java 5, an enhanced for loop (used to traverse some arrays and objects) is introduced, which is mainly used for arrays
whlie cycle
-
whlie is the most basic loop. The syntax 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 to end the loop by invalidating an expression
-
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 true all the time, it will cause infinite loop (dead loop). We should try to avoid dead loop in normal business.
Dead loop will affect program performance or cause program deadlock and crash
-
Think 1 + 2 + 3 ++ 99+100
package com.chang.Control; public class Control0601 { public static void main(String[] args) { //Output 1-100; int a = 0; while (a<100){ a++; System.out.println(a); } } }
Dead cycle
package com.chang.Control; public class Control0602 { public static void main(String[] args) { //Dead cycle while (true){ //Can be used in the following cases //Waiting for client connection //Timing check //. . . . . } } }
Think 1 + 2 + 3 ++ 99+100
package com.chang.Control; public class Control0603 { //Think 1 + 2 + 3 ++ 99+100 public static void main(String[] args) { int a = 0; int sum = 0; while (a<=100){ sum = sum+a; a++; } 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.
-
do... The while loop is similar to the while loop, except that do The while loop executes at least once
-
Grammatical structure
do{ //Code statement }while(Boolean expression);
-
do... The difference between while and while:
-
whlie judges first and then executes, do While execute before Judge
-
Do...while always ensures that the loop is executed at least once! This is their main difference!
-
package com.chang.Control; public class Control0701 { public static void main(String[] args) { //Execute the code first, then judge int a = 0; do { System.out.println(a); a++; }while (a<=100); } }
While and do The difference between while
package com.chang.Control; public class Control0702 { public static void main(String[] args) { //While and do The difference between while //When while is judged to be false, the code is not executed //do...while for the first time, whether you are satisfied with the Boolean expression of while or not, execute the code first int a = 0; while (a<0){ System.out.println(a); a++; } System.out.println("================="); do { System.out.println(a); a++; }while (a<0); } }
For loop
-
Although all loop structures can use while or do While, but Java provides another statement - for loop, which makes some loop structures simpler
-
for loop structure 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 structure is as follows:
for(Initial value;Boolean expression(Conditional judgment);iteration(to update)){ //Code statement }
package com.chang.Control; public class Control0801 { public static void main(String[] args) { int a = 0;//Initial value while (a<100){//Conditional judgment System.out.println(a);//Circulatory body a+=2;//iteration } System.out.println("while End of cycle!"); System.out.println("============="); // Initial value condition judgment iteration //Shortcut keys: 100.for == for (int i = 0; i < 100; i++) {} for (int i = 0; i < 100; i++) { System.out.println(i); } System.out.println("for End of cycle!"); /* 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. Start executing the statement 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) Detect the Boolean expression again. Loop through the above procedure. */ //Dead cycle for (; ; ) { } } }
Exercise 1
Calculates the sum of odd and even numbers between 0 and 100
package com.chang.Control; public class Control0802 { 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){ oddSum+=i; }else { evenSum+=i; } } System.out.println("Even sum is:"+oddSum); System.out.println("Odd sum is:"+evenSum); } }
Exercise 2
Use the while or for loop to output the number that can be divided by 5 between 1-1000, and output 3 per line
-
for loop
package com.chang.Control; public class Control0803 { public static void main(String[] args) { //Use the while or for loop to output the number that can be divided by 5 between 1-1000, and output 3 per line for (int i = 0; i <=1000; i++) { if(i%5==0){ System.out.print(i+"\t"); // \t: horizontal skip }if(i%(5*3)==0){ System.out.print("\n"); // \n: line feed } //println output completely wraps //No line break after print output } } }
-
while Loop
package com.chang.Control; public class Control0804 { public static void main(String[] args) { //Use the while loop to output the number that can be divided by 5 between 1-1000, and output 3 per line int a = 0; while (a<=1000){ if(a%5==0){ System.out.print(a+"\t"); }if(a%(5*3)==0){ System.out.print("\n"); } a++; } } }
Exercise 3 printing the 99 multiplication table
package com.chang.Control; /* 1*1=1 1*2=2 2*2=4 1*3=3 2*3=6 3*3=9 1*4=4 2*4=8 3*4=12 4*4=16 1*5=5 2*5=10 3*5=15 4*5=20 5*5=25 1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81 */ public class Control0901 { public static void main(String[] args) { //Printing 99 multiplication table: Ideas //1. Print the first column first //2. Wrap the fixed 1 in another cycle //3. Remove duplicates //4. Adjust style for (int i = 1; i <=9; i++) { //System.out.println("i:"+i); for (int j =1;j <= i;j++){ //System.out.println("j:"+j); System.out.print(j+"*"+i+"="+(i*j)+"\t"); } System.out.println(); } //code analysis //i = 1 -- > J = 1 J < = i sets up the loop body of output j j + + J = 2 -- > J < = i does not set up the loop body of output i //i + + i = 2 -- > J = 1 J < = i establish the loop body of output j j + + J = 2 J < = i establish the loop body of output j j + + J = 3 -- > J < = i do not establish the loop body of output i //and so on } }
Enhanced For loop
-
Array focus
-
Java 5 introduces an enhanced For loop that is mainly used For arrays or collections.
-
Java enhanced for loop syntax format:
for(Declaration statements: expressions){ //Code sentence }
-
Declaration statement: declare a new local variable. The type of the variable must match the type of the array.
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: the expression is the name of the array to be accessed, or the return value is an array.
package com.chang.Control; public class Control1001 { public static void main(String[] args) { int[] a = {10,20,30,40,50};//Define an array for (int b :a){//Want to be and assign the values in the a array to b one by one; System.out.println(b); } System.out.println("=============="); for (int i = 0; i < 5; i++) { System.out.println(a[i]); } } }
break continue
-
Break in the subject part of any loop statement, you can use break to control the loop process. Break is used to force a loop to exit
Do not execute the remaining statements below the loop. (break statements are also used in switch statements)
package com.chang.Control; public class Control1101 { public static void main(String[] args) { int a = 0; while (a<100){ a++; System.out.println(a); if(a==30){ break; } } } }
-
The continue statement is used in the loop statement body to terminate a loop process, that is, to skip the statements that have not been executed in the loop body,
Then, it is determined whether to execute the cycle next time
package com.chang.Control; public class Control1102 { public static void main(String[] args) { int a = 0; while (a<100){ a++; System.out.print(" "); if(a%10==0){ System.out.println(); continue; } System.out.print(a); } } }
About goto keyword
-
The goto keyword has long appeared in programming languages. Goto is still a reserved word in Java, but it is not used correctly in the language; Java
No goto. However, in the two keywords break and continue, we can still see some shadow of goto - labeled break and continue.
-
Label refers to the identifier followed by a colon, such as label:
-
For Java, the only place where tags are used is before loop statements. The only reason to set the label before the loop is that we want to nest another one in it
Loop, because the break and continue keywords usually break the current loop, but if they are used with the tag, they will break to the place of the tag
package com.chang.Control; public class Control1103 { public static void main(String[] args) { //Print prime numbers between 101-150 //Prime number is a natural number with a value greater than 1 and no other factors except 1 and itself. //Not recommended outer: for (int i = 101; i < 150; i++) { for(int j=2;j<i/2;j++){ if (i%j==0){ continue outer; } } System.out.print(i+"\t"); } } }
Print triangles
-
Regular triangle
package com.chang.Control; public class Control1201 { //Print triangles public static void main(String[] args) { for (int i = 1; i <= 5; i++) { for (int j=5;j>=i;j--) { System.out.print(" ");//First area } for (int j = 1; j <=i; j++) { System.out.print("*");//Second area } for (int j = 1; j < i; j++) { System.out.print("*");//The third area } System.out.println(); } } }
-
-
Inverted triangle
package com.chang.Control; public class Control1202 { //Print inverted triangle public static void main(String[] args) { for (int i = 1; i <= 5; i++) { for (int j=1;j<i;j++){ System.out.print(" "); } for (int j = 5; j >=i; j--) { System.out.print("*"); } for (int j = 5; j > i; j--) { System.out.print("*"); } System.out.println(); } } }