Java control statements
Java control statements can be divided into 7 types:
Control selection structure statement
- if、if else
- switch
Control loop structure statement
- for
- while
- do while
Change the order of control statements
- break
- continue
1. If statement
The if statement belongs to the selection structure, and the if statement is also called a branch statement/conditional control statement
1 The grammatical structure of the if statement: four writing methods
The first type of
if (Boolean expression) { java statement; java statement; … }
The second type of
if (Boolean expression) { java statement; java statement; … } else { java statement; java statement; … }
The third type of
if (Boolean expression) { java statement java statement ... } else if (Boolean expression) { java statement java statement ... } else if (Boolean expression) { java statement java statement ... } else if (Boolean expression ) { Java statement java statement ... }...
The fourth type of
if (Boolean expression) { java statement java statement ... } else if (Boolean expression) { java statement java statement ... } else if (Boolean expression) { java statement java statement ... } else { java statement java statement … }…
2 Important: For the if statement in the java statement, as long as there is a branch to execute, the entire if statement ends.
3 Note: The second and fourth writing methods above have an else branch. These two methods can guarantee 100% branch execution.
4 All control statements can be nested, as long as they are properly nested.
Note: When using nesting, the code format must be perfect. [The indentation must be indented. In most cases, indentation is required to use braces]
5 When there is only one java statement in the branch of the if statement, the braces can be omitted.
System.out.println(); 负责向控制台输出
6 Receive input sentences from the user keyboard:
public class KeyInputTest
{
publid static void main(String[] args){
java.util.Scanner s = new java.util.Scanner(System.in); //第一步,创建键盘扫描器对象
输入字符:
String UserInputContent = s.next();
//第二步:调用Scanner对象的next方法开始接收用户的键盘输入
//程序执行到这里会停下来,等待用户的输入
//当用户输入的时候,并且最终敲回车的时候,输入的信息会自动赋值给userInputContent
//程序执行到这里,用户输入的信息已经到内存中了,
System.out.println("您输入了:" + UserInputContent).; //将内存的数据输入到控制台
输入数字
int num = s.nextInt(); //接收数字
System.out.println("您输入的数字是:" + num);
}
}
Correct statement:
public class IfTest01
{
public static void main(String[] args){
boolean sex=true;
if (sex){
System.out.println("男");
}else{
System.out.println("女");
}
sex=false;
if(sex) System.out.println("男"); else System.out.println("女");
}
}
Error statement:
public class IfTest02
{
public static void main(String[] args){
boolean sex=true;
if(sex)
System.out.println("男");
System.out.println("hehe"); //不加大括号的话只包括第一条语句,第二条语句不是if语句的分支java语句
else //else缺少if
System.out.println("女");
}
}
Note: A picture I saw in the learning group today is very interesting, share it.