Java基础
一、顺序结构
顺序结构是最常见的结构 , 代码按先后依次执行;
顺序结构语句有许多种
1、if语句
包括
1.if(条件 ){ 语句体};
2.if ( 条件 ){语句体一}else{ 语句体2}
3.if ( 条件一 ){ 语句体一} else if(条件二 ){语句体二}
2、switch 语句
witch表示这是switch语句
表达式的取值:byte,short,int,char
JDK5以后可以是枚举
JDK7以后可以是String
case后面跟的是要和表达式进行比较的值
语句体部分可以是一条或多条语句
break表示中断,结束的意思,可以结束switch语句
default语句表示所有情况都不匹配的时候,就执行该处的内容,和if语句的else相似。
格式为:
二、循环流程控制语句
1、for循环语句格式:
for(初始化语句;判断条件语句;控制条件语句) {
循环体语句;
}
- while循环语句
初始化语句;
while(判断条件语句) {
循环体语句;
控制条件语句;
} - do…while 语句
do {
循环体语句;
控制条件语句;
} while((判断条件语句);
三、控制循环语句
1.Break的使用场景和作用
break的使用场景:
在选择结构switch语句中
在循环语句中
离开使用场景的存在是没有意义的
break的作用:
跳出单层循环
2.continue的使用场景:
在循环语句中
离开使用场景的存在是没有意义的
continue的作用:
单层循环对比break,然后总结两个的区别
break 退出当前循环
continue 退出本次循环
代码练习在这里插入代码片
今日作业(必做)
------------------------------------------------------------------
第一题:看程序说结果,请不要提前运行?
public class Test01_01 {
public static void main(String[] args) {
int x = 1,y = 1;
if(x++==2 & ++y==2) //false x=2; y=2;
{
x =7;
}
System.out.println("x="+x+",y="+y); //x=2,y=2
int a = 1,b = 1;
if(a++==2 && ++b==2) // false a=2
{
a =7;
}
System.out.println("a="+a+",b="+b); // a=2,b=1;
}
}
public class Test01_02 {
public static void main(String[] args) {
int x = 1,y = 1;
if(x++==1 | ++y==1) // true x=2 y=2
{
x =7;
}
System.out.println("x="+x+",y="+y); //x=7 y=2
int a = 1,b = 1;
if(a++==1 || ++b==1) //true a=2 b =1
{
a =7;
}
System.out.println("a="+a+",b="+b);// a=7,b=1
boolean c = true;
if(c==false)
System.out.println("a");
else if(c)
System.out.println("b"); // b
else if(!c)
System.out.println("c");
else
System.out.println("d");
}
}
public class Test01_03 {
public static void main(String[] args) {
int x = 2,y=3;
switch(x)
{
default:
y++;
case 3:
y++;
break;
case 4:
y++;
}
System.out.println("y="+y); // y=5
}
}
第二题:分析以下需求,并用代码实现:
1.键盘录入一个整数给变量x,输出对应的变量y的值
2.x值和y值的对应关系如下:
x<0 y=-1
x=0 y=