catalogue
Process control
Input and output
Take the following code as an example:
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner scanner=new Scanner(System.in);//Create a Scanner object System.out.println("Input your name:");//Print tips String name=scanner.newxtLine();//Read and get string System.out.println("Input your age:");//Print tips int age=scanner.nextInt();//Get and get integer System.out.print(name+" is "age+" years old!")//output } }
First, we import Java. Net through the import statement util. Scanner, import is a statement to import a class, which must be placed at the beginning of the Java source code. Later, we will explain in detail how to use import in the java package.
Then, create the Scanner object and pass it into system in. System.out represents the standard output stream, while system In stands for standard input stream. Directly use system Although it is possible to read user input in, it requires more complex code, and the subsequent code can be simplified through Scanner.
After having the scanner object, to read the string entered by the user, use scanner Nextline(), to read the integer entered by the user, use scanner nextInt(). Scanner automatically converts the data type, so you don't have to convert it manually
if judgment
-
Basic syntax of if
if(){ }
Based on the calculation results in if, the JVM decides whether to execute the if statement block
-if can be used with else
if(){ }else{ }
Else is also associated with multiple if else if... series connection
-
Judge whether the reference types are equal. In Java, you can use the = = operator to judge whether the variables of value types are equal. However, to judge whether the variables of reference types are equal, = = means "whether the references are equal", or whether they point to the same object.
For example, the contents of the following two String types are the same, but they point to different objects respectively. Judge with = = and the result is false:
public class Main{ public static void main(String[] args){ String s1="hello"; String s2="HELLO".toLowerCase(); System.out.println(s1); System.out.println(s2); if(s1==s2){ System.out.println("s1==s2"); }else{ System.out.println("s1!=s2"); } } }
Output result:
hello hello s1!=s2
To determine whether the contents of variables of reference types are equal, you must use the equals() method:
public class Main{ public static void main(String[] args){ String s1="hello"; String s2="HELLO".toLowerCase(); System.out.println(s1); System.out.println(s2); if(s1.equals(s2)){ System.out.println("s1 equals s2"); }else{ System.out.println("s1 not equals s2"); } } }
Output result:
hello hello s1 equals s2
-
Please use if Else write a program to calculate body mass index BMI and print the results.
BMI = weight (kg) divided by the square of height (m)
BMI results:
Too light: below 18.5 normal: 18.5-25 overweight: 25-28 obese: 28-32 very obese: above 32
reference resources:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("Input your weight(kg):"); float weight=scanner.nextFloat(); System.out.println("Input your hight(m):"); float hight=scanner.nextFloat(); float bmi=weight/(float) Math.pow(hight, 2); System.out.println(bmi); if(bmi<18.5) { System.out.println("Too light"); }else if(bmi<25){ System.out.println("normal"); }else if(bmi<28) { System.out.println("overweight"); }else if(bmi<32) { System.out.println("Obesity"); }else { System.out.println("Very fat"); } } }
switch multiple selection
In addition to the if statement, there is also a condition judgment, which is to execute different branches according to the result of an expression.
-
Basic syntax of switch
int option=1; switch(option){ case 1: System.out.println("Selected 1"); break; case 2: System.out.println("Selected 2"); break; case 3: Sysytem.out.println("Selected 3"); break; default: System.out.println("Not selected"); break; }
result:
Selected 1
-
Function of default when the value of option is not in the branch, it will go to the content corresponding to default.
-
The function of break ends. If there is no break, the next branch will be executed until break jumps out of the selected branch;
Both and default are unforgettable in switch; -
option can also be string switch. In case of string matching, it is the comparison content;
-
switch expression
int opt; switch (fruit) { case "apple": opt = 1; break; case "pear": case "mango": opt = 2; break; default: opt = 0; break;
Starting from java12 (12, 13, 14), switch is upgraded to a simpler expression. The new syntax has no penetration effect. Don't write break again;
public class Main{ public static void main(String[] args){ String fruit="apple"; int opt=switch(fruit){ case "apple"->1; case "pear","mango"->2; default->0; };//Assignment statement with; ending System.out.println("opt="+opt); } }
-
Yield if we need complex statements, we can also write many statements and put them in {...} Then, use yield to return a value as the return value of the switch statement:
public class Main{ public static void main(String[] args){ String fruit="orange"; int opt=switch(fruit){ case "apple"->1; case "pear","mango"->2; default->{ int code=friut.hanshCode(); yield code; } } } }
-
Practice using switch to realize a simple game of stone, scissors and cloth.
reference resources:
import java.util.Scanner; public class Main { public static void main(String[] args) { while(true) { System.out.println("Rock(stone)"); System.out.println("Scissors(scissors)"); System.out.println("Paper(cloth)"); System.out.println("end&continue"); System.out.println("Input your chioce:"); Scanner sc=new Scanner(System.in); String chioce=sc.next(); int comp=(int)(Math.random()*3);//Math.random() indicates the floating-point type of [0,1] System.out.print("Computer:"); judge(chioce,comp); System.out.println("Enter 0 to continue the game!"); String s=sc.next(); if(s.equals("end"))break; } } public static void judge(String chioce,int comp) { String flag=null; switch(comp) { case 0: System.out.println("Rock"); flag="Rock"; break; case 1: System.out.println("Scissors"); flag="Scissors"; break; case 2: System.out.println("Paper"); flag="Paper"; break; default : break; } panduan(chioce,flag); } public static void panduan(String chioce,String flag) { if(chioce.equals(flag)) { System.out.println("it ends in a draw!"); }else { if((chioce.equals("Rock")&&flag.equals("Scissors"))||(chioce.equals("Scissors")&&flag.equals("Paper"))||(chioce.equals("Paper")&&flag.equals("Rock"))) { System.out.println("you win!"); }else { System.out.println("you lose!"); } } } }
while Loop
-
Basic grammar
while(Conditional expression){ }
When the conditional expression is true, the statement in {} will be executed, and then loop again (no break);
Avoid dead loops, that is, the conditional expression is always true;
-
Practice using while to calculate the sum from m to n:
reference resources:
public class Main{ public static void main(String[] aegs){ int sum=0; int m=20; int n=100; while(m!=(n+1){ sum+=m; m++; } System.out,println(sum); } }
do while loop
While loop is to judge the loop condition first, and then execute the loop. The other do while loop is to execute the loop first, and then judge the conditions. When the conditions are met, continue the loop, and exit when the conditions are not met.
Basic syntax:
do{ }while(Conditional expression);//Finally, add;
-
Practice using the do while loop to calculate the sum from m to n.
public class Main { public static void main(String[] args) { int sum = 0; int m = 20; int n = 100; do { sum+=m; m++ } while (m!=(n+1)); System.out.println(sum); } }
for loop
-
Basic grammar
for(Initial conditions; Cycle detection conditions; Update counter after cycle){ ///Execute statement }
-
Use the for statement flexibly. The for loop can lack initial conditions, loop conditions and loop update statements
-
For each loop Java provides another for each loop, which makes it easier to traverse arrays;
public class Main{ public static void main(String[] args){ int[] ns={1,12,23,34,45,6} for(int n:ns){ System.out.println(n); } } }
Output result:
1 12 23 34 45 6
Compared with the for loop, the variable n of the for each loop is no longer a counter, but directly corresponds to each element of the array. The for each loop is also more concise. However, the for each loop cannot specify the traversal order or get the index of the array.
In addition to arrays, the for each loop can traverse all "iteratable" data types, such as List, Map, etc.
-
Exercise 1 Given an array, please use the for loop to output each element in reverse order: Reference:
public class Main { public static void main(String[] args) { int[] ns = { 1, 4, 9, 16, 25 }; for (int i=ns.lenght;i>0;i--) { System.out.println(ns[i]); } } }
2. Use the for each loop to sum each element of the array: Reference:
public class Main { public static void main(String[] args) { int[] ns = { 1, 4, 9, 16, 25 }; int sum = 0; for (int n:ns) { sum+=n; } System.out.println(sum); // 55 } }
3. PI can be calculated by formula: Reference:
public class Main { public static void main(String[] args) { double pi = 0; for (long i=1,j=-1;i<=999999999;i++) { j=-1*j; double a=j*(2*i-1); pi+=4*(1/a); } System.out.println(pi); } }
break and continue
-
Break during the loop, you can use the break statement to jump out__ Current__ Cycle.
-
continue break will jump out of the current loop, that is, the whole loop will not be executed. continue ends this cycle in advance and directly continues to execute the next cycle.