Scanner的学习
Scanner对象的next()和nextLine()方法的区别
next()
-
一定要读取到有效字符后才可以结束输入
-
对输入有效字符之前遇到的空白,next()方法将输出空白前的字符
-
next()方法不能得到带有空格的字符串
-
例如 输入hello world 会输出hello
代码示例如下:
import java.util.Scanner; public class Demo04 { public static void main(String[] args) { //创建一个扫描器对象,用于接收键盘数据 Scanner scanner = new Scanner(System.in); System.out.println("使用next方式接收"); //判断用户有没有输入字符串 if(scanner.hasNext()){ String str = scanner.next(); System.out.println("输出的内容为:"+str); } //凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉 scanner.close(); } }
nextLine()
-
以enter为结束符,可以输出回车前的所有字符
-
可以获得空白
-
例如 输入hello world 会输出 hello world
代码示例如下
import java.util.Scanner; public class Demo05 { public static void main(String[] args) { //创建一个扫描器对象,用于接收键盘数据 Scanner scanner = new Scanner(System.in); System.out.println("使用nextLine方式接受"); //判断用户有没有输入字符 if(scanner.hasNextLine()){ String str1 = scanner.nextLine(); System.out.println("输出的内容为:"+str1); } //凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉 scanner.close(); } }
Scanner其他方法的使用
nextInt()和nextDouble方法
import java.util.Scanner;
public class Demo06 {
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方法的简单应用
输入多个数字,并求其总和和平均数,每输入一个数字用回车确认,通过输入非数字来结束输入并输出执行结果
代码如下:
import java.util.Scanner;
public class Demo07 {
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++;
sum = sum + x;
System.out.println("你输入了第"+m+"个数据,然后当前结果sum="+sum);
}
System.out.println(m+"个数的和为:"+sum);
System.out.println(m+"个数的平均数是:"+sum/m);
scanner.close();
}
}