自学JavaSE(四)--流程控制
1.Scanner对象
Java提供的工具类,我们可以获取用户输入。java.util.Scanner是Java5的特性
基本语法:
Scanner s = new Scanner(System.in);
通过Scanner累的next()与nextLine()方法获取输入的字符串,在读取前我们一般需要使用hasNext()与hasNextLine()判断是否还有输入的数据
package com.qinbanzhang.scanner;
import java.util.Scanner;
public class Demo01 {
public static void main(String[] args) {
//创建一个扫描器对象,用于接受键盘数据
Scanner scanner = new Scanner(System.in);
System.out.println(scanner);
//判断用户有没有输入字符串,如果为真
if (scanner.hasNext()){
//使用next方法接收
String str = scanner.next(); //程序会等待用户输入完毕
System.out.println(str);
}
//凡是io流需要关闭节省资源
scanner.close();
}
}
/**
* 输入hello world
* 输出hello
*/
package com.qinbanzhang.scanner;
import java.util.Scanner;
public class Demo02 {
public static void main(String[] args) {
//创建一个扫描器对象,用于接受键盘数据
Scanner scanner = new Scanner(System.in);
System.out.println(scanner);
//判断用户有没有输入字符串,如果为真
if (scanner.hasNextLine()){
//使用nextLine方法接收
String str = scanner.nextLine(); //程序会等待用户输入完毕
System.out.println(str);
}
//凡是io流需要关闭节省资源
scanner.close();
}
}
/**
* 输入hello world
* 输出hello world
*/
hasNext()与hasNextLine()的区别
hasNext()遇到空白则不再接受输入(输入hello world 输出hello) hasNextLine()是以Enter为结束符可以接收空白,hasNextLine()更常用
package com.qinbanzhang.scanner;
import java.util.Scanner;
public class Demo03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//和
double sum = 0;
//输入的个数
int m = 0;
while (scanner.hasNextDouble()) {
double x = scanner.nextDouble();
m = m+1;
sum = sum + x;
System.out.println("总和:"+ sum );
System.out.println("你输入了第"+m+"个数字,平均数为:"+(sum/m));
}
System.out.println("总和:"+ sum );
System.out.println("平均值:"+ (sum/m));
scanner.close();
}
}
2.顺序结构
Java的基本结构就是顺序结构,除非特别指明,否则都是顺序从上到下执行
package com.qinbanzhang.stuct;
public class ShunxuDemo {
public static void main(String[] args) {
System.out.println("hello1");
System.out.println("hello2");
System.out.println("hello3");
System.out.println("hello4");
}
}
/**
* hello1
* hello2
* hello3
* hello4
*/
3.选择结构
if单选结构
if双选结构
if多选结构
掏钱的if结构
switch多选结构
1.if单选结构
if(布尔表达式){
执行语句
}
2.if多选结构
if(布尔表达式){
执行语句
}else if(布尔表达式){
执行语句
}else if(布尔表达式){
执行语句
}else(布尔表达式){
执行语句
}
3.switch
package com.qinbanzhang.stuct;
public class Switch {
public static void main(String[] args) {
char grade = 'b';
switch (grade) {
case 'a' -> System.out.println("优秀");
case 'b' -> System.out.println("良好");
case 'c' -> System.out.println("中等");
case 'd' -> System.out.println("差");
default -> System.out.println("看不懂");
}
}
}
//增强switch适用于新版java12
4.循环结构
while循环
do while循环
for循环
while循环
while(条件判断){
执行语句
}
do while循环
do{
执行语句至少执行一次
}while(条件判断)
do while和while的区别是do while不管表达式真假 至少会执行一次执行语句
for循环
for(初始值;条件判断;更新){
}
//快捷键:10.for
5.增强for循环
package com.qinbanzhang.stuct;
public class For {
public static void main(String[] args) {
int[] numbers = {10,20,30,40,50};
for (int b:numbers) {
System.out.println(b);
}
}
}
6.break和continue
break停止当前循环
continue跳过程序中某一次循环

浙公网安备 33010602011771号