Process Control
Scanner for Human-Program Interaction
We can get user input through the Scanner class
Scanner Basic Syntax:
Scanner sc=new Scanner(System.in);
-
Gets the input string through the next() and nextLine() methods of the Scanner class;
-
hasNext() and hasNextLine() are generally used to determine whether there is input data before reading.
if (sc.hasNext()){//Default to true without == //Receive data using next String str=sc.next(); //The program waits for user input to complete System.out.println("The output is:"+str); }
nextLine():
//end with carriage return
1. The nextLine() method returns all the characters before entering the carriage return;
2. You can get blanks.
next():
//End with space
1. You must read valid characters before you can end the input.
2. The next() method will automatically remove blanks before valid characters are entered;
3. Use the blank space entered after a valid character as separator or terminator only after entering it;
4. next() cannot get a string with spaces.
//Input data Scanner sc=new Scanner(System.in); //receive data String str=sc.nextLint(); //Close sc.close();
For common methods of the Scanner class:
-
String nextLine() receives a string entered by the console
-
int nextInt() receives an int data input from the console
-
double nextDouble() receives a double data input from the console
-
note: The Scanner class for data input of type char does not provide a method for directly entering type char. Characters can be obtained from next() or nextLine () using the chatAt() method
/*next().charAt(0) Get the first character from a string entered by the console */ /*"SHKO".charAt(1) Output result is H */
if selection structure
-
grammar
if(Boolean expression){ //Execute when Boolean expression is true }else{ //Execute when Boolean expression is flase } //Multiple Selection Structure //Execute only one if(Boolean expression 1){ //Executed when Boolean expression 1 is true }else if(Boolean Expression 2){ //Executed when Boolean expression 2 is true }else if(Boolean expression 3){ //Executed when Boolean expression 3 is true }else{ //None of the above is satisfactory }
/* If statement has at most one else statement; If statements can have several else if, which must precede the else statement*/
switch multi-selection structure
A switch case statement determines whether a variable is equal to a value in a series of values, each of which is called a branch.
switch(expression){ case value1: //Statement 1 case value2: //Statement 2 break; ````````//There can be any number of case statements default: //Statement n+1 } /*Format description: Expression: take the value byte, short, int, char, JDK5 can be an enumeration later, JDK7 can be a String later. case: Following is the value to be compared with the expression. break: Represents an interrupt, an end, used to end a switch statement. default: Indicates that when all situations do not match, the contents are executed there, similar to else of the if statement. Execution process: The expression is evaluated first. Compare with the values after the case in turn, and if there is a corresponding value, the corresponding statement will be executed, and the break will end during execution. If all the values behind the case do not match the values of the expression, the body inside default is executed and the program is terminated. */
char grade='A'; switch(grade){ case 'A': //implement System.out.println("excellent"); case'B': System.out.println("good"); break; default: System.out.println("Unknown Level"); } /*The console output is: excellent good But we found that A should be good because our break is in case'B', It will take all the output before the break (we call the case through) =====At this point we should add break after each case */
Decompilation
Open the diagram:
Click on My Computer, paste the address in the navigation bar, find the corresponding demo class file copy, find the demo that needs decompiling in IDEA, right mouse button, open the folder where you are located (show in Explorer) and paste the previously copied class file into this folder. A new demo will be generated in IDEA and opened for viewing.
Cyclic structure
The most basic while loop
while(Boolean expression){ //Statement Body }
As long as the Boolean expression is true, the loop will continue to create an endless loop, which we should try to avoid.
Most of us need a way to invalidate the expression to end the loop, and a few cases require a continuous loop, such as server request response listening;
//1+2+ ......+100 public static void main(String[] args) { //1+......+100 int i=0; int sum=0; while (i<=100) { sum = sum + i; i++; } System.out.println(sum);//5050
do...while loop
For while, a loop cannot be entered if the condition is not met, do... while loop is executed at least once;
//Initialization expression//1 do{ //Statement body 1 // 3 //Statement body 2 // 4 }while(Boolean expression); // 2 //The execution order is 134>234>234...2 until the condition is not met
for loop
Is the most efficient and flexible circular structure
for(initialize variable;Boolean expression;Variable Update){ //Statement Body }
/* Initialization steps are performed first, and a type can be declared, one or more loop control variables can be initialized, or empty statements can be made;*/
Use shortcut keys in IDEA such as: 100. ForPlus carriage return auto-generated
//1-100 integer divisible by 5 with 3 outputs per line public static void main(String[] args) { for (int i = 5; i <=100; i++) { if (i%5==0){ System.out.print(i+"\t"); } if (i%(5*3)==0){ System.out.print("\n"); //System.out.println(""); } } } /* print Is not newline output println Is Line Break Output */
//multiplication table public static void main(String[] args) { //Print first column, nested loop, remove duplicates, adjust style for (int i = 1; i <= 9; i++) { for (int j = 1; j <=i; j++) { System.out.print(j+"*"+i+"="+(j*i)+"\t"); } System.out.println();//Line Break } } /* Total number of loops in nested loops = number of outer loops * number of inner loops */
The difference between for and while:
-
The variable controlled by the control condition statement is no longer accessible after the for loop ends
Yes, when the while cycle ends, you can continue to make. If you want to continue making, you can do so while.
-
Otherwise, it is recommended to make_for. The reason is that at the end of the for loop, the variable disappears from memory and can
Memory efficiency.
-
Make for when the number of cycles is known, and make for when the number of cycles is unknown
while.
Enhance for cycle
public static void main(String[] args) { int[] numbers={10,20,30,40,50}; //Traversing through array elements for (int x:numbers){ System.out.print(x+" "); } /*Amount to for (int i = 0; i < 5; i++) { System.out.print(numbers[i]+" "); } */ }
jump statement
break
break can be used in the main part of any loop statement to force the exit of the loop, not the end of the program.
continue
Continue is used in the body of a loop statement to terminate a loop process, that is, to skip statements that are not executed in the loop statement and then decide whether to execute the loop next time. (End this cycle and continue with the next one)
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(" ");//Inverted triangle with upper left space } for (int j = 1; j <=i ; j++) { System.out.print("*");//Triangles of Part Two } for (int j = 1; j <i ; j++) { System.out.print("*");//Triangles of Part Three } System.out.println(); } }