Scanner的作用类似于python的input但是不仅限于此,在初学阶段一般用于输入数据、字符串等。
1.next和nextline方式的区别
next()与nextLine()比较:
next()方式接收的特点:
1、一定要读取到有效字符后才会结束输入
2、有效字符前后的空白或者空白之后的数据都会被忽略掉
3、在没有输入有效字符前,按下回车键只会换行不能结束输入
4、next() 不能得到带有空格的字符串(因为会自动忽略掉空格之后的内容)
nextLine()方式接收的特点:
1、以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
2、可以获得空白,注意不输入任何字符、空格的情况下,按下回车同样会结束输入。
2.next方式接受数据
import java.util.Scanner;
public class demo1 {
public static void main(String[] args) {
//创建扫描器对象,接受键盘数据
Scanner scanner = new Scanner(System.in);
System.out.println("使用next方式接收:");//下面会用nextline方式接收进行对比
//判断用户有没有输入字符串
if(scanner.hasNext()){
//使用next方式接收
String str = scanner.next();
System.out.println("输出的内容为:"+str);
}
//Scanner属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉
scanner.close();
}
}
下面是运行效果图片:
注意:输入字符前输入了多个换行符和空格,如果没有键入内容,按回车是不会结束的。
键入内容后按回车,发现只有Hello被打印出来,说明用next方式接受数据,会自动接受输入的第一串数据,自动忽略掉前后的空格和空格后面的内容
3.nextline方式接收数据
import java.util.Scanner;
public class demo2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("使用nextline()方式接收:");
//判断用户有没有输入字符串
if (scanner.hasNextLine()){//这里换成了用hasNextLine()判断
String string = scanner.nextLine();
System.out.println("输入的内容是:"+string);
}
//不要忘记关闭scanner
scanner.close();
}
}
运行效果图:



