JAVA流程控制
条件判断
/*
语法:if(条件判断){
执行语句
}else if(条件判断1){
执行语句
}else if(条件判断2){
执行语句
}else{
执行语句
}
*/
public class Demo01{
public static void main(String[]args) {
int socre = 65;
if (socre>60 && socre <70) {
System.out.println("成功");
}else if(socre>70){
System.out.println("0.0");
}else {
System.out.println("失败");
}
}
}
条件必须是True或者Fales
多重if当遇到第一个满足表达式的条件时,执行当前if的语句,不会再往下走
switch分支判断(适合等值判断)
switch(表达式){
case 常量1:
执行语句一;
break;
case 常量2:
执行语句二;
break;
case 常量3:
执行语句三
break;
default:
执行语句
break;
}
条件表达式只能是byte,short,char,int,String
public class Demo02{
public static void main(String[]args) {
int a =50;
switch(a) {
case 10:
a +=10;
break; //跳出switch
case 50:
a +=20;
break;
default:
a+=50;
break;
}
System.out.println(a);
}
}
如果case中没有break,就会穿透执行,不管是否匹配,都会执行,知道遇到break;但是前提是找到了一个匹配的case进入后没有break才会穿透执行.
三元运算符
X ? Y : Z
如果x为true执行Y,否则执行Z;
public class Demo04 {
public static void main(String[]args) {
int sex = 2;
char result = sex ==1? '男':'女'; //三元运算符的结果类型是由表达式的结果的类型决定的
System.out.println(result);
//三元运算嵌套
Scanner s = new Scanner(System.in);
System.out.print("请输入你的分数:");
int score = s.nextInt();
String res = score>90?"优秀":(score >60?"及格":"不及格");
System.out.print(res);
}
}
循环结构
while循环
/*
语法:
while(表达式){
循环体
}
表达式的结果是true就执行,为false就结束
*/
1234567
/*
输出一百以内的偶数和
*/
public class Demo05 {
public static void main(String[]args) {
int i =1;
int result =0;
while(i<=100) {
//i = (i%2 ==0)?result+=i++:++i;
if(i%2==0) {
result +=i;
}
i++;
}
System.out.print(result);
}
}
1234567891011121314151617
do…while…
/*
do{
循环体
}while(表达式);
*/
12345
public class Demo06 {
public static void main(String[]args) {
//输出100到1000的水仙花数
int i =100;
do {
//获取个位数
int g = i%10;
//获取十位数
int s =(i/10)%10;
//获取百位数
int b =i/100;
if((g*g*g+s*s*s+b*b*b)==i) {
System.out.println(i+"是水仙花数");
}
```
i++;
}while(i<1000);
}
```
}
12345678910111213141516171819
for循环
for(表达式1;表达式2;表达式3) {循环体;}
1
在第一次进入的时候,不会执行表达式3
//++i
for(int i=0;i<10;++i) {
System.out.println(i);
}
/*
输出结果
0
1
2
3
4
5
6
7
8
9
*/
//i++
for(int i=0;i<10;i++) {
System.out.println(i);
}
在for循环中,使用判断条件i++和++i的结果相同,但是运行时间上相比,++i更快,因为Java中i++语句是需要一个临时变量取存储返回自增前的值,而++i不需要
自加的条件相当于在执行了循环体后才执行
public class Demo01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//打印五行
for(int i=0;i<5;i++) {
System.out.println("====");
}
//打印四行五列
for(int i=0;i<4;i++) {
for(int j=0;j<5;j++) {
System.out.print("=");
}
System.out.println("");
}
}
}
123456789101112131415161718
/*
打印九九乘法口诀
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//外层控制行
for(int i=1;i<=9;i++) {
//内层控制列
for(int j=1;j<=i;j++) {
System.out.print(j+"*"+i+"="+i*j+"\t");
}
System.out.println("");
}
}
}