程序的结构
- 顺序结构
- 选择结构(if语句实际上就是一种选择结构的体现)
- 循环结构
if 选择语句
public class Opdemo4 {
public static void main(String[] args)
{
int x = 3;
int y = 10;
System.out.println("------比较开始------");
if(x>y)
{
System.out.println("x比y大");
}
if(x<y)
{
System.out.println("x比y小");
}
System.out.println("比较完成");
}
}
选择结构
if……else语句
public class Ifelsedemo {
public static void main(String[] args)
{
int x= 3;
if(x%2==1)
{
System.out.println("X是奇数");
}
else
{
System.out.println("x是偶数");
}
}
}
三目运算符
使用三目运算符时,操作数有3个,其格式如下:
- 变量= 条件判断?表达式1:表达式2
例如,现在要求两个数之间的最大的一个数
public class Maxdemo {
public static void main(String[] args)
{
int x = 3;
int y = 10;
int max = 0;
if(x<y)
{
max = y ;
}
else
{
max = x;
}
System.out.println("最大值为:"+max);
}
}
if…… else if…… else语句
多条件判断
public class Moreifelsedemo {
public static void main(String[] main)
{
int x =3;
if(x==1)
{
System.out.println("x的值是1!");
}
else if (x==2)
{
System.out.println("x的值是2!");
}
else if (x==3)
{
System.out.println("x的值是3!");
}
else
{
System.out.println("x的值不是1、2、3之中的一个!");
}
}
}
switch语句
对于多条件判断在java中也提供了一种专门的语句,此语句是switch语句
注意一点:
在使用switch进行表达式判断的时候,一定要注意:在表达式中只能使用数字和字符,以后的章节中会出现枚举。
public class Switchdemo {
public static void main(String[] args)
{
int x = 3;
int y = 10;
char oper = '+';
switch(oper)
{
case '+':
{
System.out.println("x+y = "+(x+y));
break;
}
case '-':
{
System.out.println("x-y = "+(x*y));
break;
}
case '*':
{
System.out.println("x/y = "+(x/y));
break;
}
default :
{
System.out.println("未知的操作!");
}
}
}
}
但是对于以上的操作中,读者可以发现每个语句之后都会存在一个break,此语句表示退出整个switch()语句,如果不写上此语句,则所有的操作将在第一个满足条件之后的语句之后全部输出,直到遇到break为止。
循环结构
- while循环
- do……while循环
- for循环
while循环
例如使用一个while循环,进行累加操作。
public class whiledemo {
public static void main(String[] args)
{
int x = 1;
int sum = 0;
while(x<=10)
{
sum += x;
x++;
}
System.out.println("1----->10累加的值 sum= "+sum);
}
}
do……while 循环
下面用do……while来修改之前的操作
public class dowhiledemo {
public static void main(String[] args)
{
int x = 1;
int sum = 0;
do
{
sum += x;
x++;
}
while(x<=10);
System.out.println("1----->10累加的值 sum = "+sum);
}
}
循环在操作中也可以进行嵌套的使用
例如,现在要打印一个九九乘法表,就需要双重循环
public class for2demo {
public static void main(String[] args)
{
for(int i = 1;i<9;i++)
{
for(int j = 1;j<i;j++)
{
System.out.println(i+"*"+j+"="+(i*j)+"\t");
}
System.out.println();
}
}
}
中断语句
break
break语句可以强迫程序中断,当程序执行到break语句的时候,跳出当前循环,继续执行循坏外的下一个语句。
如果break语句出现在嵌套循环中的内层循环,则break语句指挥跳出当前层的循环。
一般来说,在开发中会结合if语句一起出现。
public class breakdemo {
public static void main(String[] args)
{
for(int i = 0;i<=9;i++)
{
if(i==3)
{
break;
}
System.out.println("i="+i);
}
}
}
continue
continue语句可以强迫程序跳到循环的起始处,当程序运行到continue语句时,即会停止运行剩余的循环主体,并回到循环的开始处继续执行。
使用continue就是中断一次循环执行。
总结
- 任何语言都会包含三种功能:顺序、选择、循环
- 选择结构:if、if……else、if……else if……else、switch
- 循环:while、do……while、for循环
- 两种中断关键字:break、continue