条件判断三种形式:
1)三元运算符
2)if-else
3)switch
1.三元运算符
1)公式:(条件表达式)?表达式1:表达式2;
如果条件true,运算后的结果表达式1,如果条件false,运算结果表达式2;
返回的结果只有true和false(其实就是if else条件判断语句)
2)使用三元运算符的好处:简化if-else的形式。弊端:因为是一个运算符,所以运算完必须有一个结果。
3)实例:获取两个数中的最大数:
int a = 1 ;
int b = 2 ;
System.out.println(a>b? a:b);//判断a和b那个大并且输出那个值。
“=”表示赋值, “==”表示boolean
if(a=1 && b=1) {} //错误
if(a==1 && b==1) {} //正确
2.if 条件判断
例子:打印空心“0” if else 没有else的话出现的情况是:
0
00
0 00
0000
int h=1;
while(h < 5) {
int l=1;
while(l<=h) {
if(h==3 && l==2 ) {
System.out.print(" ");
}else{
System.out.print("0");
} //都要有括号
l++; //都会走的
}
h++;
System.out.println();
}
if语句的几种情况:
//if语句的几种情况
//1)if-else if-else(一组) 形式 只会走一个分支
int a = 10;
if(a > 5) {
System.out.println("a is big");
}
else if(a < 5) {
System.out.println("a is small");
}
else{
System.out.println("a is big");
}
//2)并行if 都会走,两个if之间没有关系
if(a > 5) {
System.out.println("a is big");
}
if(a < 5) {
System.out.println("a is small");
}
//3)一组 只会走一个
if(){
}else{
}
//4)两个if之间没有关系
if(){
}else{
}
if(){
}
if语句的问题:
打印空心三角形
while(...){
if(a > 5) {
System.out.println(" ");
}
else{
System.out.println("0");
}
//一定要注释,否则都会走
//System.out.println("0");
}
public static void main (String [] args) {
//double b = 90; //基本数据
Double b = new Double(90); //Double 对象类型
if (b < 0 && b > 100) {
System.out.println("非法成绩");
}
else if(0 <= b && b < 60) {
System.out.println("不及格");
}
else if(60 <= b && b < 70) {
System.out.println("差");
}
else if(70 <= b && b < 80) {
System.out.println("中");
}
else if(80 <= b && b < 90) {
System.out.println("良");
}
else {
System.out.println("优");
}
}
3.switch条件判断
语句超过1条的,都用{}括起来!!!
int a = 5;
if(a < 1 || a > 12) {
System.out.println("未知月份");
}else {
int season = (a - 1) / 3;
switch(season) {
case 0:{
System.out.println("春");
break;
}
case 1:{
System.out.println("夏");
//break; //注销这个break的结果就是打印夏和秋,因为没有终止他的程序
}
case 3:{
System.out.println("秋");
break;
}
default:
System.out.println("冬");
}
byte a=1;
switch(a) {}
short b=3;
switch(b) {}
int c=3;
switch(c) {}
char d='3';
switch(d) {}
//double e=3; 错误示范
//switch(e) {}
long f=3;//错误示范
switch(f) {}