next():
1.一直读取到有效字符,遇到空格会结束输入

2.在读取有效字符之前遇到的空格会自动删去

3,不会得到带空格的字符串
nextLine():
以enter为结束符,会输出enter之前的所有字符包括空格

代码
Scanner sc=new Scanner(System.in);
System.out.println("使用next方式接受:");
//判断用户有没有输入字符串
if(sc.hasNext()) {
String str=sc.next();
System.out.println(str);
}
//IO流的类如果不关会一直占用资源
sc.close();
Scanner sc=new Scanner(System.in);
System.out.println("使用nextLine方式接受:");
//判断用户有没有输入字符串
if(sc.hasNextLine()) {
String str=sc.nextLine();
System.out.println(str);
}
//IO流的类如果不关会一直占用资源
sc.close();
本文介绍了Java中Scanner类的next()和nextLine()两个方法在处理用户输入时的不同点。next()会忽略前导空格并只读取到第一个空格前的字符,而nextLine()则会读取整行,包括空格。示例代码展示了这两种方法的使用。
1191





