文章目录
1. 运算符和表达式
整数被0除会产生一个异常,而浮点数被0除将会得到无穷大或NaN
1)数学函数和常量
Math类的调用方式
Math.sqrt(x), Math.pow(x, a), Math.sin, Math.log, Math.PI, Math.E
或在源文件顶部采用
import static java.lang.Math.*;
Math.pow()
方法有两个double类型的参数,其返回结果也是double类型
2)逻辑运算与位运算
- 逻辑运算符: && || !
- 位运算符:位与( & ) 、位或( | )、位非( ~ )、位异或( ^ ),左移( << )和右移( >> )
3)其他的常用运算符
自增自减运算符只针对变量 - 4++
非法
// 二元运算符
x += 4;
// 自增自减
int p = 7;
int q = 7;
int a = 2 * ++p; // 16
int b = 2 * q++; // 14
// 布尔运算符
System.out.println(3 != 7); // true
// 三元运算符 x < y ? x :y
System.out.println(2 > 3 ? 2 : 3); // 3
2. 控制流程
😃 条件语句和循环语句
1)块作用域
- 块确定了变量的作用域
- 一个块可以嵌套在另一个块中,但不能在嵌套的两个块中声明同名的变量
public class Main { public static void main(string[] args) { int n; { int k; int n; // 编译报错 } } }
2)条件语句和选择语句
条件语句
条件必须用括号括起来,else
部分可选
if (condition) statement
if (condition) statement1 else statement2
if (condition1) statement1 else if(condition2) statement2 else statement3
if(x > y) { System.out.println(x); } else if(x < y) { System.out.println(y); } else { System.out.println("Equal"); }
选择语句
😃 有时避免很多if-else
金字塔结构,可采用swith
语句
注意:若在
case
分支语句的末尾没有break
语句,则会接着执行下一个case
分支语句(无论条件是否成立都会执行)
switch(choice)
{
case 1:
...;
break;
case 2:
...;
break;
default:
...;
break;
}
3)循环语句
while循环
while (condition) statement
while(balance < goal) { balance += payment; years++; }
do statement while (condition)
- 循环体至少执行一次do { balance += payment; years++; }while(balance < goal);
for循环
for(int i = 10; i > 0; i--){
System.out.println(x);
}
等价于
int i = 10;
while(i > 0){
System.out.println(i);
i--;
}
中断语句
break
退出循环continue
中断当前循环的后续操作,继续下一次循环