1.顺序结构
2.分支结构if else,switch case
3.循环结构
4.break和continue
1.小插曲——Scanner
从键盘获取不同类型的变量:使用Scanner
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int i =sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();
boolean b = sc.nextBoolean();
//对于char类型,没有相关类型,只能获取字符串
//注:输入的数据要与接受的类型相同或者相容才可以,否则会出现InputMismatchException异常
2.分支结构:
2.1 if-else三种结构
- 只有if:if(条件表达式){}
- 二选一:if(条件表达式){} else{}
- 多选一:if(条件表达式){} else if(条件表达式){}… else{}
2.2 switch…case
switch(表达式){
case 常量1:语句1;//break;
case 常量2:语句2;//break;
......
case 常量n:语句n;//break;
default:语句; //break;
}
注意:
①switch结构中的表达式,只能是如下六中数据结构类型之一:byte/short/char/int/枚举类型(JDK5.0新增)/string类型(JDK7.0新增)
②case后面必须是确定的常量,不能是范围age>8不可以。
③default可选,位置也是随意的。
输出:other zero.(defalut执行结束后,仍然顺序向下执行,直到找到break)
3.循环结构
while
do while
for
4.break和continue
break和continue的特殊用法——标签:
可以指定标签,跳出循环:
public static void main(String args[]){
label:for (int i=0;i<=4;i++){
for (int j = 1;j<=10;j++){
if(j%4==0){
break label;
}
System.out.print(j);
}
}
}
//123
public static void main(String args[]){
label:for (int i=0;i<=4;i++){
for (int j = 1;j<=10;j++){
if(j%4==0){
continue label;
}
System.out.print(j);
}
}
}
//123123123123123
质数的输出:
public static void main(String args[]){
boolean flag = true;
for(int i=1;i<=100;i++){
flag = true;
for (int j = 2;j<i;j++){
if(i%j==0){
flag = false;
}
}
if(flag==true)
System.out.println(i);
}
}
//优化
public static void main(String args[]){
boolean flag = true;
for(int i=1;i<=100;i++){
flag = true;
for (int j = 2;j<=Math.sqrt(i);j++){//优化二:对所有有效,但是break过滤了非质数,所以这个地方对质数有效
if(i%j==0){
flag = false;
break;//优化一:对非质数的起作用
}
}
if(flag==true)
System.out.println(i);
}
}
//特殊做法
public static void main(String args[]){
lable:for(int i=2;i<=100;i++){
for (int j = 2;j<=Math.sqrt(i);j++){
if(i%j==0){
continue lable;
}
}
System.out.println(i);
}
}