java流程控制
1.用户交互Scanner
通过Scanner类来获取用户的输入
- 基础语法
Scanner s = new Scanner(System.in); - 通过Scanner类的next()与nextLine()方法获取输入的字符串,在读取前我们一般需要使用hasNext()与hasNextLine()判断是否还有输入的数据。
- next()不能带有空格的字符串,nextLine可以获取空白。
package com.company;
import java.util.Scanner;
public class Demo02 {
public static void main(String[] args) {
//创建一个扫描器对象,用于接收键盘数据
Scanner scanner = new Scanner(System.in);
System.out.println("使用nextLine方式接收:");
//判断用户有没有输入字符串
if(scanner.hasNextLine()){
//使用next方式接收
String str = scanner.nextLine();
System.out.println("输出的内容是:"+str);
}
//凡是属于IO流的类如果不关闭会一直占用资源
scanner.close();
}
}
2.选择结构
- if语句
if (条件){
//语句
}else if (条件){
//语句
}else if (条件){
//语句
}else {
//语句
}
- switch语句
switch (expression){
case value:
//语句
break;//可选
case value:
//语句
break;//可选
default://可选
//语句
}
3.循环结构
- while循环
while(布尔表达式){
//循环内容
}
- do while循环
do{
//代码语句
}while(布尔表达式);
- for循环
for(初始化;布尔表达式;更新){
//代码语句
}
for(声明语句:表达式){
//代码语句
}
package com.company;
public class Demo03 {
public static void main(String[] args) {
int[] numbers = {10,20,30,40,50};
for (int x:numbers){
System.out.println(x);
}
}
}
4.break & continue
- break用于强行退出循环,不执行循环中剩余的语句。
- continue用于终止某次循环过程。