----------- android培训、java培训、java学习型技术博客、期待与您交流! ------------
if..else语句(判断语句)
格式:if (判断语句) {
执行语句;
}
例题:class IfTest {
public static void main(String[] args) {
/*int x = 3;
if(x>1){
System.out.println("a");//a
}else if(x>2){
System.out.println("b");
}else if(x>3){
System.out.println("c");
}else{
System.out.println("d");
}
//if语句的每一种格式都是一个单条语句,每种格式最后只能走一条分支
int x = 3;
if(x>1){
System.out.println("a");//a
}
if(x>2){
System.out.println("b");//b
}
if(x>3){
System.out.println("c");
}else{
System.out.println("d");//d
}*/
//if的嵌套语句
int x = 1, y = 1;
if (x == 1) {
if (y == 1) {
System.out.println("a");
}else {
System.out.println("b");
}
}else {
if (y == 1) {
System.out.println("c");
}else {
System.out.println("d");
}
}
}
}
格式for(初始化表达式;循环条件表达式:循环后的操作表达式){
执行语句;
}
例题class ForForTest2 {
public static void main(String[] args) {
//打印正的直角三角形
/*for (int x = 1;x <= 5;x++){
for (int y = 1;y <= x;y++){
System.out.print("*");
}
System.out.println();
}*/
格式:
/*
while语句格式:
while(条件表达式){
执行语句;
控制循环次数;
例题:lass WhileDemo1 {
public static void main(String[] args) {
int x = 1;
while(x <= 10) {
System.out.println("x =" + x);
x++;
}
}
}
格式:
do while语句格式:
do{
执行语句;
控制循环次数;
}while(条件表达式);
class DoWhileDmeo1 {
public static void main(String[] args) {
int x = 11;
do{
System.out.println("x =" +x);
x ++;
}
while (x <= 10);
//while和do while的区别
//while是如果条件不满足,就不执行里面的语循环体
//do while 无论条件是否满足,都会至少执行一次循环体
}
}
格式:switch(表达式){
case 取值1:
执行语句;
break;
case 取值2:
执行语句;
break;
......
}
}
例题:class BreakTest {
public static void main(String[] args) {
/*int x = 4;
for(int i = 1; i<=10; i++){
//当i等于x的时候,退出循环
if(i==x){
break;
}
System.out.println("i = " + i);
}*/
int y = 4;
for(int i = 1; i<=10; i++){
//当i等于x的时候,退出循环
if(i==y){
continue;
}
System.out.println("i = " + i);
}
}
}