[JAVA] Logic control in java

 Author's homepage: paper jie's blog

Author of this article: Hello everyone, I am paper jie, thank you for reading this article, welcome to build three companies.

This article is included in the "JAVASE Grammar Series" column, which is carefully crafted for college students and beginners in programming. The author spent a lot of money (time and energy) to build it, and wiped out the basic knowledge of javaSE, hoping to help readers.

Other columns: "Detailed Algorithm Explanation", "C Language", etc.

Content sharing: This issue will give a general explanation of the logic control in JAVA~

foreword

In the front, we made a simple overview of java, explaining its data types, variables, and operators. In this article, we will explain the logic control in java in detail, so stay tuned~

branch structure

if statement

Grammar Format 1

if(布尔表达式){
// 语句
}

In java, if the boolean expression evaluates to true, the statement in the if is executed, otherwise it is not executed

Take a chestnut: if Ah San is older than 90 years old, it is longevity, otherwise it is not

int age = 95;
if(age >= 90){
System.out.println("阿三活太久了吧");
}

Grammar format 2

if(
布尔表达式){
// 语句1
}else{
// 语句2
}

If the result of the Boolean expression is true, execute the statement in the if, otherwise execute the statement in the else. 

Take a chestnut: If Ah San is over 90 years old, he has lived too long, otherwise he will be a short-lived ghost

int age = 95;
if(age >= 90){
System.out.println("阿三活太久了吧");
}else {
System.out.println("阿三是短命鬼");
}

Grammar format 3

if(
布尔表达式1){
// 语句1
}else if(布尔表达式2){
// 语句2
}else{
// 语句3
}

If expression 1 is true, execute statement 1, otherwise expression 2 is true, execute statement 2, otherwise execute statement 3  

Take a chestnut: There is a student's exam that needs to be evaluated. Those whose scores are between [90, 100] are excellent, those whose scores are before [80, 90) are good, and those whose scores are between [70, 80) are medium If the score is between [60, 70), it is a passing score. If the score is between [0, 60), it is a failure. Others are wrong data 

if(
score >= 90){
System.out.println("优秀");
}else if(score >= 80 && score < 90){
System.out.println("良好");
}else if(score >= 70 && score < 80){
System.out.println("中等");
}else if(score >= 60 && score < 70){
System.out.println("及格");
}else if(score >= 0 && score < 60){
System.out.println("不及格");
}else{
System.out.println("错误数据");
}

Note: In the following code, although both methods are legal, it is recommended to use style 1 in Java, but do not bring the C code style to Java.

// 风格1-----> 推荐
int x = 10;
if (x == 10) {
// 语句1
} else {
// 语句2
} 
//风格二
int x = 10;
if (x == 10)
{
// 语句1
} e
lse
{
// 语句2
}

When you write code, be careful not to appear behind the brackets; the following code is a case, and an extra semicolon is written, causing the semicolon to become the statement body of the if statement, and the code in { } has become A block of code that has nothing to do with an if 

int x = 20;
if (x == 10);
{
System.out.println("hehe");
} /
/ 运行结果
hehe

Another problem is that if/else statements do not need braces. But you can also write statements (only one statement). At this time, else matches the closest if. But we do not recommend writing this way in actual development. preferably with braces

int x = 10;
int y = 10;
if (x == 10)
if (y == 10)
System.out.println("aaa");
else
System.out.println("bbb");

switch statement 

grammar

switch(表达式){
case 常量值1:{
语句1;
[break;]
}
case 常量值2:{
语句2;
[break;]
}

……

default:{
内容都不满足时执行语句;
[break;]
}
}

Its process:

1. Calculate the value of the expression first

2. Compare with the case in turn, once there is a corresponding match, execute the statement under this item, until it ends when a break is encountered

3. When the value of the expression does not match the listed items, execute default 

Take a chestnut:

int day = 1;
switch(day) {
case 1:
System.out.println("星期一");
break;
case 2:
System.out.println("星期二");
break;
case 3:
System.out.println("星期三");
break;
case 4:
System.out.println("星期四");
break;
case 5:
System.out.println("星期五");
break;
case 6:
System.out.println("星期六");
break;
case 7:
System.out.println("星期日");
break;
default:
System.out.println("输入有误");
break;
}

Note:
The constant value after multiple cases cannot be repeated

The brackets of switch can only contain the following types of expressions:

Basic types: byte, char, short, int, pay attention not to be long type

Reference type: String constant string, enumeration type

loop structure

while loop 

Basic syntax:

while(循环条件){
循环语句;
}

If the loop condition is true, execute the loop statement; otherwise end the loop 

Take a chestnut:

nt num = 1;
while (num <= 10) {
System.out.println(num);
num++;
}

Notice:

1. Similar to if, the statement below while can not write { }, but only one statement can be supported when it is not written. It is recommended to add { }

2. Similar to if, the { after while is suggested to be written on the same line as while.

3. Similar to if, do not write more semicolons after while, otherwise the loop may not be executed correctly. 

int num = 1;
while (num <= 10); {
System.out.println(num);
num++;
}

At this time, in the statement body of while (this is an empty statement), the actual { } part has nothing to do with the loop. At this time, the loop condition num <= 10 is always true, resulting in an infinite loop of code 

break

break It can make the loop end early 

Take a chestnut:

nt num = 100;
while (num <= 200) {
if (num % 3 == 0) {
System.out.println("找到了 3 的倍数, 为:" + num);
break;
} n
um++;
}

When the code encounters a break, it will jump out and stop the loop

continue

The function of continue is to skip this cycle and immediately enter the next cycle 

Take a chestnut:

int num = 100;
while (num <= 200) {
if (num % 3 != 0) {
num++; // 这里的 ++ 不要忘记! 否则会死循环.
continue;
} System.out.println("找到了 3 的倍数, 为:" + num);
num++;
}

When the continue statement is executed, it will immediately enter the next loop so that the print statement below will not be executed 

for loop

basic grammar

for(表达式①;布尔表达式②;表达式③){
表达式④;
}

Expression 1: It is used to initialize the initial value setting of the loop variable, which is executed at the very beginning of the loop, and only once.
Expression 2: The loop condition, if it is full, the loop continues, otherwise the loop ends.
Expression 3: The loop variable update method 

Its process is: ①②③④--->②③④--->②③④--->②③④--->②③④--->②③④--->...--->② is false, and the loop ends. 

Take a chestnut:

for (int i = 1; i <= 10; i++) {
System.out.println(i);
}

drawing analysis

 Notice:

1. Similar to if, the statement below for can not write { }, but only one statement can be supported when it is not written. It is recommended to add { }

2. Similar to if, the { after for is suggested to be written on the same line as while.

3. Similar to if, do not write more semicolons after for, otherwise the loop may not be executed correctly.

4. Like the while loop, use continue to end a single loop, and break to end the entire loop 

do while loop

basic grammar

do{
循环语句;
}while(循环条件);

The loop statement is executed first, and then the loop condition is determined. If the loop condition is met, the execution continues, otherwise the loop ends. 

Take a chestnut:

int num = 1;
do {
System.out.println(num);
num++;
} while (num <= 10);

Notice:

1. Do not forget the semicolon at the end of the do while loop

2. It is more recommended to use for and while.
 

sequential structure

The sequential structure is executed line by line in the order in which the code is written. If you adjust the order of the code will also change:

System.out.println("aaa");
System.out.println("bbb");
System.out.println("ccc");
// 运行结果
aaa
bbb
ccc
System.out.println("aaa");
System.out.println("ccc");
System.out.println("bbb");
// 运行结果
aaa
ccc
bbb

input Output

output to the console

Basic syntax:

System.out.println(msg);
System.out.print(msg);
// Output a string, with newlines
// Output a string, without newlines

System.out.printf(format, msg); // formatted output

The content of println output comes with \n, print does not have \n

The formatted output method of printf is basically the same as that of printf in C language. 

Take a chestnut:

System.out.println("hello world");
int x = 10;
System.out.printf("x = %d\n", x)

input from the keyboard

Use Scanner to read strings/integers/floats 

import java.util.Scanner; // 需要导入 util 包
Scanner sc = new Scanner(System.in);
System.out.println("请输入你的姓名:");
String name = sc.nextLine();
System.out.println("请输入你的年龄:");
int age = sc.nextInt();
System.out.println("请输入你的工资:");
float salary = sc.nextFloat();
System.out.println("你的信息如下:");
System.out.println("姓名: "+name+"\n"+"年龄:"+age+"\n"+"工资:"+salary);
sc.close(); // 注意, 要记得调用关闭方法
// 执行结果
请输入你的姓名:
张三
请输入你的年龄:
18
请输入你的工资:
1000
你的信息如下:
姓名: 张三
年龄:18
工资:1000.0

When looping to enter multiple data, use ctrl + z to end the input (ctrl + z on Windows, ctrl + d on Linux / Mac).

guess the number game

Here is a guessing number game for everyone based on the above knowledge. This code was also explained in detail in C in the previous blog. Here is the code directly:

import java.util.Random;
import java.util.Scanner;;
class Test {
public static void main(String[] args) {
Random random = new Random(); // 默认随机种子是系统时间
Scanner sc = new Scanner(System.in);
int toGuess = random.nextInt(100);
// System.out.println("toGuess: " + toGuess);
while (true) {
System.out.println("请输入要输入的数字: (1-100)");
int num = sc.nextInt();
if (num < toGuess) {
System.out.println("猜小了");
} else if (num > toGuess) {
System.out.println("猜大了");
} else {
System.out.println("恭喜你,猜对了");
break;
}
} s
c.close();
}
}

Guess you like

Origin blog.csdn.net/paperjie/article/details/131972557