打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Java中关于nextInt()、next()和nextLine()的理解

先看解释:

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问题。

看下面代码:

 1 import java.util.Scanner; 2  3 public class MaxMap { 4     public static void main(String[] args){ 5         Scanner cin = new Scanner(System.in); 6         int n = cin.nextInt(); 7         String str = cin.nextLine(); 8         System.out.println("END"); 9         }10 }            

执行后结果:

从执行结果上看,貌似直接跳过了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");        }}

在看下面代码:

 1 import java.util.Scanner; 2  3 public class MaxMap { 4     public static void main(String[] args){ 5         Scanner cin = new Scanner(System.in); 6         String n = cin.next(); 7         //cin.nextLine(); 8         String str = cin.nextLine(); 9         System.out.println("END");10         System.out.println("next()read:"+n);11         System.out.println("nextLine()read:"+str);12     }13 }

执行结果:

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

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

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

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

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Java中两种基本的输入方式小结
Java中Scanner的nextInt(),next(),nextLine()方法总结
Scanner常用的方法
Scanner 中关于 nextInt()与nextLine()的问题
Java之Scanner
Java Scanner 类
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服