关于Java中扫描仪next()与nextLine()的区别

首先,next()一定要读取到有效字符后才可以结束输入,对输入有效字符之前遇到的空格键、Tab键或Enter键等结束符,next()方法会自动将其去掉,只有在输入有效字符之后,next()方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符。

简单地说,next()查找并返回来自此扫描器的下一个完整标记。完整标记的前后是与分隔模式匹配的输入信息,所以next()方法不能得到带空格的字符串。

而nextLine()方法的结束符只是Enter键,即nextLine()方法返回的是Enter键之前的所有字符,它是可以得到带空格的字符串的。

记得有个博客上有一句话(next()是我只要文字,而nextLine()是啥我都要)

实例1:

public class H_Z03 {

public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  System.out.println("输入s:");
  String s = in.nextLine();
  System.out.println("输入s1");
  String s1 = in.next();
  System.out.println(s);
  System.out.println(s1);
  }

}

输出结果:

输入s:
张三
输入s1
李四
张三
李四

这个结果是输入正常,显示也正常的。

示例2

public class H_Z04 {

public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  System.out.println("输入s:");
  String s = in.next();
  System.out.println("输入s1");
  String s1 = in.nextLine();
  System.out.println(s);
  System.out.println(s1);
  }

}

输入输出结果:

输入s:
张三
输入s1
张三

这个出现了问题只让输入“张三”,

查询相关资料发现:

String s1 = in.nextLine();

接受空格之后的字符(包括回车、空格、空格之后的字符)

测试结果如下:

public class H_Z05 {

public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  System.out.println("输入s:");
  String s = in.next();
  System.out.println("输入s1");
  String s1 = in.nextLine();
  System.out.println(s);
  System.out.println(s1);
  }

}

输入输出结果:

输入s:
张三 李四
输入s1
张三
 李四

总结:

nextLine()会自动接收next()之后的字符,但是这个指的是对同一个对象。

解决方法:

public class H_Z06 {

public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  System.out.println("输入s:");
  String s = in.next();
  System.out.println("输入s1");

   in.nextLine();
  String s1 = in.nextLine();
  System.out.println(s);
  System.out.println(s1);
  }

}

输入输出结果:

输入s:
张三 李四
输入s1
王五
张三
王五

猜你喜欢

转载自www.cnblogs.com/hhxz/p/9708888.html