黑马程序员——运算符与语句

时间:2023-02-19 13:32:42

------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

  运算符与语句

运算符

   运算符顾名思义就是一种用作运算的符号,它用于执行程序代码的运算,通常针对一个以上操作数项目来进行运算。运算符包括:算数运算符(+)、赋值运算符(=)、比较运算符(==,!=)、逻辑运算符、位运算符、三元运算符。比较运算符的结果都是boolean型,也就是要么是true,要么是flase。位运算符<<左移 :  其实就是乘以2的移动的位数次幂;>>右移 :  其实就是除以2的移动的位数次幂。>>右移: 最高位补什么由原来的数据的最高位值而定,如果最高位为0,右移后,用0补空位,如果最高位为1,右移后,用1补空位。>>>无符号右移: 无论最高位是什么,右移后,都用0补。逻辑运算符:&与,|或,^异或,!非,&& AND()短路,|| OR短路。三元运算符:{(条件表达式)?表达式1:表达式2;}如果条件为true,运算后的结果是表达式1;如果条件为false,运算后的结果是表达式2。

语句

语句一般包括三大类:判断语句、选择语句、循环语句。if语句(判断语句)包含条件判断部分、执行代码部分,它有三种格式:if;if else;if elseif  else。 下面就是一个判断语句的小程序。 class IfTest
{
public static void main(String[] args)
{
//需求1:根据用户定义的数值不同,打印对应的星期。

int num = 8;
if(num==1)
System.out.println("星期一");
else if(num==2)
System.out.println("星期二");
else if(num==3)
System.out.println("星期三");
else if(num==4)
System.out.println("星期四");
else if(num==5)
System.out.println("星期五");
else if(num==6)
System.out.println("星期六");
else if(num==7)
System.out.println("星期天");
else
System.out.println("没有对应的星期。");
//需求2:根据用户指定的月份,打印该月份所属的季节。
//3,4,5春季  6,7,8夏季  9,10,11秋季  12,1,2冬季
int x = 14;
if(x>12 || x<1)
System.out.println(x+" 没有对应的季节。");
else if(x>=3 && x<=5)
System.out.println(x+"月 春季");
else if(x>=6 && x<=8)
System.out.println(x+"月 夏季");
else if(x>=9 && x<=11)
System.out.println(x+"月 秋季");
else

System.out.println(x+"月 冬季");
}
}
switch语句有四个特点:1,,switch语句的类型只有四种:byte、short、int、char。2,case之间和default没有顺序,先执行第一个 case,没有匹配的case执行default。3,结束switch语句的两种情况:遇到break,执行到switch语句结束。4,如果匹配的case或者default没有对应的break,那么程序将不再判断case,而是会继续向下执行,运行可以执行的语句,直到遇到break或者switch结尾结束。if与switch语句很像,如果判断的具体数值不多,而且符合byte short int char这四种类型,虽然两个语句都可以使用,建议使用switch语句,因为效率更高。下面就是一个选择语句的小程序。 class SwitchTest
{
public static void main(String[] args)
{
int x = 15;

switch(x)
{
case 3:
case 4:
case 5:
System.out.println(x+"月 春季");
break;
case 6:
case 7:
case 8:
System.out.println(x+"月 夏季");
break;
case 9:
case 10:
case 11:
System.out.println(x+"月 秋季");
break;
case 12:
case 1:
case 2:
System.out.println(x+"月 冬季");
break;
default:
System.out.println(x+" 没有对应的季节。");
}
}
}
循环语句主要包括三种:while循环、for循环、do-while循环,当事先不知道要执行多少次程序时就用到了while循环语句。下面就是一个循环语句的小程序。 class ForForDemo
{
public static void main(String[] args)
{
for(int x =0;x<3;x++)
{
for(int y =0;y<4;y++)
{
System.out.print("*");
}
System.out.println();//只有一个功能就是换行。
}
System.out.println("-------------");
for(int x=0;x<5;x++)
{
for(int y=x;y<5;y++)
{
System.out.print("*");
}
System.out.println();
//z--;
}
}
}

------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------