流程控制Scanner
```java
package com.zishi.scanner;
import java.util.Scanner;
public class Demo01 {
public static void main(String[] args) {
//创建一个扫描器对象,用于接受键盘数据
Scanner scanner = new Scanner(System.in);
System.out.println("使用next方法接收:");
//判断用户有没有输入字符串
if (scanner.hasNext()){ //next()不能得到带有空格的字符串 以空格为结束符
//使用next方式接收
String str =scanner.next(); //hello world
System.out.println("输出的内容为:"+str); //hello
}
//凡是属于IO流的类如果不关闭会一直占用资源,要养成用完就关掉的好习惯
scanner.close();
}
}
```
```java
package com.zishi.scanner;
import java.util.Scanner;
public class Demo02 {
public static void main(String[] args) {
//通过scanner接收数据
Scanner scanner = new Scanner(System.in);
System.out.println("使用nextLine方法接收:");
//判断是否还有输入
if(scanner.hasNextLine()){ //NextLine() 以Enter为结束符 可以有空白
String str = scanner.nextLine(); //hello world
System.out.println("输出的内容为:"+str); //hello world
}
scanner.close();
}
}
```
```java
package com.zishi.scanner;
import java.util.Scanner;
public class Demo03 {
public static void main(String[] args) {
//通过scanner接收数据
Scanner scanner = new Scanner(System.in);
System.out.println("请输入:");
String str = scanner.nextLine();
System.out.println("输入内容为"+str);
scanner.close();
}
}
```
```java
package com.zishi.scanner;
import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;
import java.util.Scanner;
public class Demo04 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//从键盘接收数据
int i = 0;
float f = 0.0f;
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("输入的不是浮点数");
}
scanner.close();
}
}
```
```java
package com.zishi.scanner;
import java.util.Scanner;
public class Demo05 {
public static void main(String[] args) {
//我们可以输入多个数字,并求其总和与平均数,每输入一个数字用回车确认,通过输入非数字来结束输入并输出执行结果:
Scanner scanner = new Scanner(System.in); //ctrl + alt + v 补全 new左侧代码
//和
double sum = 0;
//计算输入多少个数字
int m = 0;
System.out.println("请输入数字:");
//通过while循环判断是否还有输入,并在里面对每一次进行求和统计
while (scanner.hasNextDouble()) {
double x = scanner.nextDouble();
m++; //m = m+1;
sum = sum+x;
System.out.println("你输入了第"+m+"个数据,总和sum="+sum);
}
System.out.println(m +"个数字的总和为:"+sum);
System.out.println(m+"个数字的平均值为:"+(sum/m));
scanner.close();
}
}
```