if语句
- ;表示独立的一块语句
- if() 后面没分号
- 一句话可以省略大括号,不建议这样。
//if语句
int a=10;
int b=5;
int c;
if(a>7&& b<3) //后面没有分号
{
System.out.println("mmm");
}
if else第2种用法
//if语句 字符串判断
String name="xiaoyang";
if(name.equals("xiaowei"))
{
System.out.println("this is my friend");
}
else
{
System.out.println("this is not my friend");
}
if else 第3种用法
//if语句 else if
float salor=13000f;
if(salor<5000)
{
System.out.println("初级工程师");
}
else if(salor<10000)
{
System.out.println("中级工程师");
}
else if(salor<15000)
{
System.out.println("高级工程师");
}
else
{
System.out.println("资深工程师");
}
Scanner —输入
if嵌套
int age=60;
boolean gender=false; //true代表女 false代表男
if (gender==true)
{
if(age<0)
{
System.out.println("年龄非法");
}
else if(age<6)
{
System.out.println("女婴儿");
}
else if(age<20)
{
System.out.println("少女");
}
else
{
System.out.println("少妇");
}
}
else if(gender==false)
{
if(age<0)
{
System.out.println("年龄非法");
}
else if(age<6)
{
System.out.println("男婴儿");
}
else if(age<20)
{
System.out.println("少男");
}
else
{
System.out.println("中年男人");
}
}
else
{
System.out.println("性别非法");
}
switch 语句
- switch 小括号支持byte short char int 枚举 String 。 不支持long
- case 后面是常量(字面量)
- case 后面常量不能重复
- case 后面要有空格
switch(i)
{
case 1:
;
break;
default:
…
break;
}
int month = 10;
switch (month)
{
case 3:
System.out.println("春天");
break;
case 7:
System.out.println("夏天");
break;
// 省略
default:
System.out.println("月份错误");
break;
}
switch 优化方法
case 3:
case 4:
case 5:
System.out.println("春天");
break;
case 6:
case 7:
case 8:
System.out.println("夏天");
break;
误区如下.没有写break
//运行结果:因为没有break. case 2 之后继续执行
// 456
// 666
// 789
int i=2;
switch(i)
{
case 1:
System.out.println("123");
case 2:
System.out.println("456");
case 3:
System.out.println("666");
default:
System.out.println("789");
}