Java basic self-study notes-Chapter 5: Loop

Chapter 5: Loop

One.while loop

1. Flow chart
while loop
2. Attention

Only when the loop contains only one statement or no statement, you can omit the curly braces.

In loop control, do not use floating-point values ​​to compare for equality, because floating-point values ​​are approximate values.

3. Classic case

int i=1;
while(i<10)
    if((i++)%2==0)
        System.out.print(i+" ");//3 5 7 9

Two. do-while loop

1. Flow chart The
do-while loop
other two are pre-test loops, and do-while is post-test loop

Three. for loop

1. Flow chart
for loop
2. Grammar

for (initial operation; loop continuation condition; operation after each iteration) ( loop body; statement group; } break: jump out of the current loop continue: jump out of the current iteration return: jump out of the current method





3. Attention

It is a good habit to declare variables in the initial operation of the for loop

The initial actions can be separated by commas

for(int i=0,j=0;i+j<10;i++,j++){
    
    }

Operations after each iteration can be separated by commas

forint i=0;i<10;System.out.println(i),i++)

In infinite loop

for(;true;){
    
    }

while(true){
    
    }//建议用这种

Four. Input and output redirection

1. When the amount of data is large, you can use input and output redirection

java 类名 < input.txt//向input.txt中读文件
java 类名 > output.txt//向output.txt中写文件
java 类名 < input.txt > output.txt//从input.txt中读,再写入output.txt文件中

2. Specific cases
Insert picture description here
Use input redirection
Insert picture description here
Integers are separated by spaces in the txt text
Insert picture description here
Use output redirection
Insert picture description here
Insert picture description here

Five. Bit operator

Operator description
& Bit and
| Bit or
^ Bit and or
~ Negate
<< Shift left
>> Right shift
>>> Unsigned right shift

1. Left shift

int y=10<<2;//00001010->00101000  结果为40

Binary moves two bits to the left and adds two zeros

2. Right shift

int y=10>>2;//00001010  ->  00000010   结果为2
int y=-10>>2;//结果为-3

Shift positive numbers to the right to complement 0,
negative numbers Shift to the right to complement 1

3. Shift right unsigned bit

int y=10>>>2;//结果为2

No matter positive or negative, add 0

V. Summary

Through the study of Chapter 5, I have learned three kinds of loops, while loop, do-while loop and for loop. They are used in different scenarios and can be transformed into each other most of the time. Use continue and break as little as possible to improve the code. readability. Input and output redirection solves the problem of large data volume very well, and the shift operation is very efficient when performing binary calculations.

Come on! Chapter 6 To Be More...

Guess you like

Origin blog.csdn.net/weixin_42563224/article/details/104233381