流程控制学习
public static void main(String[] args) {
int i = 0;
float f = (float) 1.1;
Scanner scanner = new Scanner(System.in);
System.out.println("请输入整数:");
if (scanner.hasNextInt()) {
i = scanner.nextInt();
System.out.println("输入整数:" + i);
} else {
System.out.println("你没输入整数");
}
System.out.println("请输入小数:");
if (scanner.hasNextFloat()) {
f = scanner.nextFloat();
System.out.println("输入小数:" + f);
} else {
System.out.println("你没输入小数");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
用户输入
Scanner scanner = new Scanner(System.in);
记得关流,scanner.close();
public static void main(String[] args) {
double sum = 0;//总和
int m = 0;//个数
Scanner scanner = new Scanner(System.in);
System.out.println("请输入数字:");
while (scanner.hasNextDouble()) {
double v = scanner.nextDouble();
m++;
sum = sum + v;
System.out.println("你输入第" + m + "个数据,当前总和为" + sum);
}
System.out.println("个数:" + m);
System.out.println("平均数:" + (sum / m));
scanner.close();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
顺序结构
选择结构:
if单选泽结构
if(布尔表达式为true){
//执行
}
1
2
3
if双选择结构
if(){
//执行true
}else{
//执行false
}
1
2
3
4
5
if多选择结构
if(true){
//选项1
}else if(){
//选项2
}else if(){
//选项3
}else{
//false
}
1
2
3
4
5
6
7
8
9
嵌套的if结构
if(true){
if 1为true执行代码
if(true){
if 2为true执行代码
}
}
1
2
3
4
5
6
switch多选择结构
String name="王泽林";
switch(name){
case"帅哥":
System.out.println("帅哥");
break;
case"美女":
System.out.println("美女");
break;
case"王泽林":
System.out.println("王泽林");
break;
default:
System.out.println("弄啥嘞");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
while循环
while(true){
//为true则一直执行
}
1
2
3
do…while循环
do{
//至少执行一次
}while(true)
1
2
3
for循环
for (int i = 0; i < 100; i++){
System.out.println(i);
}
1
2
3
增强for循环
foreach
break和continue
break:跳出当前整个循环
continue:跳过这个,继续执行
————————————————
版权声明:本文为CSDN博主「Wangzelindiyiming」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/m0_49161684/article/details/114745512