java学习日记——循环,选择结构
选择结构(if,switch)
如果我们需要做一个判断和选择,那我们需要一个选择的结构。那if和switch就能满足我们的需求。
简单来说就是判断一个条件是否成立成立就执行,不成立就跳过。
if
if(判断条件){
满足 判断条件(true),就执行此大括号里面的内容
}
if(判断条件){
满足 判断条件(true),就执行此大括号里面的内容
}
if(判断条件){
满足 判断条件(true),就执行此大括号里面的内容
}
注意:没有写在一起的if结构相互之间,不互斥
public static void main(String[] args) {
int a = 5;
if (a<10) {
System.out.println(a);
}
}
———————————————————————————————————————
else if
if(判断条件A){
满足 判断条件A(true),就执行此大括号里面的内容,后面的else-if不执行
}else if(判断条件B){
满足 判断条件B(true),就执行此大括号里面的内容
}else if(判断条件A){
满足 判断条件A(true),就执行此大括号里面的内容,后面的else-if不执行
}else if(判断条件B){
满足 判断条件B(true),就执行此大括号里面的内容
public static void main(String[] args) {
int a = 10;
if (a<10) {
System.out.println(a);
} else {
a=a+1;
System.out.println(a);
}
}
———————————————————————————————————————
switch
switch(x){//x是 变量或者一个表达式:该值的类型,java规定的类型
case 变量的可能值1: 功能语句;break;
case 变量的可能值2: 功能语句;break;
case 变量的可能值3: 功能语句;break;
…
default:功能语句;break;
}
public static void main(String[] args) {
int a=1;
switch (a) {
case 1:
System.out.println("优");
break;
case 2:
System.out.println("良");
break;
case 3:
System.out.println("差");
break;
default:
System.out.println("错误数据");
break;
}
}
循环(for,do while,while)
for和do while的区别:do while无论如何都是执行一次
——————————————————————————————————————
do while
do{
// 循环体
}while(条件);
public static void main(String[] args) {
int a=1;
do {
a++;
System.out.println(a);
} while (a<10);
}
———————————————————————————————————————
while
int i = 0;//A循环初始化语句
while( i<=10 ){//B循环判断语句
// 循环体具体做什么事情//C循环功能语句
i++;//D循环后语句
}
public static void main(String[] args) {
int a=1;
while (a<10) {
a++;
System.out.println(a);
}
}
———————————————————————————————————————
for
for(初始A;条件判断B;循环后操作C){
//循环体C
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}