流程控制
1、用户交互Scanner
1)通过scanner类获取用户的输入:
2)首先创建一个扫描器对象,用于接收键盘数据;
Scanner scanner = new Scanner(System.in);
3)读取数据前,可使用hasNext()和hasNextLine()判断是否有输入的数据;
4)通过next()和nextLine()方法获取输入的字符串;
5)关闭scanner。
(凡是属于IO流的类如果不关闭会一直占用资源,因此用完之后就要关掉。)
import java.util.Scanner; public class Demo01 { public static void main(String[] args) { //创建一个扫描器对象,用于接收键盘数据 Scanner scanner = new Scanner(System.in); System.out.println("使用nextLine方式接收:"); //判断用户有没有输入字符串 if (scanner.hasNextLine()){ String str = scanner.nextLine(); System.out.println("输入的内容为:"+str); } //凡是属于IO流的类如果不关闭会一直占用资源,因此用完之后就要关掉。 scanner.close(); } }
public class Demo02 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("请输入:"); String str = scanner.nextLine(); System.out.println("输入的内容为:"+str); scanner.close(); } }
注:
next():读到有效字符才可结束输入,有效数字前的空白无效,有效输入后的空白为结束符。
nextLine():返回所有字符及空白 ,以Enter为结束符。
hasNextInt():判断是否有整数型数据输入
2、顺序结构
从上到下执行
3、选择结构
if选择结构:
if(){
}else if(){
}else(){
}
switch多选择结构:switch中的变量类型可以是byte,short,int,char,String
public static void main(String[] args) { char grade = 'A'; //case穿透,匹配一个具体的值 switch (grade){ case 'A': System.out.println("优秀。"); break; case 'B': System.out.println("良好。"); break; default: System.out.println("成绩无效。"); break; } }
4、循环结构
while循环:
while(){
}
do...while循环:先执行后判断,至少执行一次
do {
sum = sum + i;
i++;
}while (i<= 100)
for循环:
for (初始化;布尔表达式;更新){
}
快捷键:100.for //执行100次
fori + 回车
增强for循环:
声明语句:声明新的局部变量,该变量的类型必须与数组元素的类型匹配,作用域限定在循环语句块,其值与此时数组元素的值相等。
表达式:表达式是要访问的数组名,或者是返回值为数组的方式。
for(声明语句:表达式){
}
int[] numbers = {1,2,3}; //遍历数组的每一个元素并赋值给x for (int x:numbers){ System.out.println(x); }
5、break&continue
break跳出循环
continue结束当前循环,进入下一次循环