结果next():
1.next()不能得到带有空格的字符串。
2.以空白作为分隔符或者结束符。
3.空白之后的字符不会显示到输出结果中。
4.一定要读取到有效的字符后才可以结束输入。
代码如下:
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()){
String s = scanner.next();
System.out.println("输出的内容为:"+s);
}
//凡是属于io流的类都要关闭,不然会一直占用资源
scanner.close();
}
}
使用next方式接收:
hello world
输出的内容为:hello
nextLine():
1.以回车(Enter)作为结束符,返回的是回车之前所有的字符。
2.可以获得空白。
代码如下:
import java.util.Scanner;
public class nextLine {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("使用nextLine方式接收:");
if(scanner.hasNextLine()){
String s = scanner.nextLine();
System.out.println("输出的内容为:"+s);
}
scanner.close();
}
}
使用nextLine方式接收:
hello world
输出的内容为:hello world