先看解释:

nextInt(): it only reads the int value, nextInt() places the cursor in the same line after reading the input.

next(): read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine():  reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

看完之后nextInt()、next()和nextLine()的区别已经很清楚了,我觉得最容易出错的就是cursor问题。

看下面代码:

 import java.util.Scanner;

 public class MaxMap {
public static void main(String[] args){
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
String str = cin.nextLine();
System.out.println("END");
}
}

执行后结果:

从执行结果上看,貌似直接跳过了String str = cin.nextLine();这行代码。

其实不然,原因是:nextInt()只读取数值,剩下"\n"还没有读取,并将cursor放在本行中。nextLine()会读取"\n",并结束(nextLine() reads till the end of line \n)。

如果想要在nextInt()后读取一行,就得在nextInt()之后额外加上cin.nextLine(),代码如下

import java.util.Scanner;

public class MaxMap {
public static void main(String[] args){
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
cin.nextLine();
String str = cin.nextLine();
System.out.println("END");
}
}

在看下面代码:

 import java.util.Scanner;

 public class MaxMap {
public static void main(String[] args){
Scanner cin = new Scanner(System.in);
String n = cin.next();
//cin.nextLine();
String str = cin.nextLine();
System.out.println("END");
System.out.println("next()read:"+n);
System.out.println("nextLine()read:"+str);
}
}

执行结果:

 原因:next()只读空格之前的数据,并且cursor指向本行,后面的nextLine()会继续读取前面留下的数据。

    想要读取整行,就是用nextLine()。

    读取数字也可以使用nextLine(),不过需要转换:Integer.parseInt(cin.nextLine())。

注意在next()、nextInt()与nextLine()一起使用时,next()、nextInt()往往会读取部分数据(会留下"\n"或者空格之后的数据)。

最新文章

  1. css3元素简单的闪烁效果(html5 jquery)
  2. tomcat文件服务配置
  3. thinkphp中文验证码不能显示的问题
  4. commonJS — 事件处理(for Event)
  5. 2440 lcd10分钟休眠修改
  6. MS SqlSever一千万条以上记录分页数据库优化经验总结【索引优化 + 代码优化】[转]
  7. 【Merge K Sorted Lists】cpp
  8. 开发设计模式(一)Command模式
  9. win7重装系统时,使用PE工具箱进入系统看到的“C盘变成0.2G,D盘变成48G左右”这是什么回事?
  10. Windows 10 TH2
  11. git入门大全
  12. console.log()的作用是什么
  13. SpringMVC 知识整理
  14. 阿里云pai项目使用说明
  15. spring-java项目中连接redis数据库
  16. FPM四:用OVP做查询跳转到明细
  17. 《剑指offer》-数字在排序数组中出现的次数
  18. 尚硅谷面试第一季-09SpringMVC中如何解决POST请求中文乱码问题GET的又如何处理呢
  19. IDE0022 使用方法的表达式主体
  20. 7.纯 CSS 创作一个 3D 文字跑马灯特效

热门文章

  1. NFS工作原理
  2. zip-gzip-bzip2_压缩文件
  3. MySQL数据库基础(四)(子查询与链接)
  4. MySQL数据库基础(MySQL5.7安装、配置)
  5. Hibernate自动生成实体类注解(转)
  6. Java经典编程题50道之三十四
  7. 搭建VUE项目的准备(利用vue-cli来构建项目)
  8. 初识Vue——模板语法
  9. Ajax检测用户名是否已经注册
  10. UART知识总结