必威体育Betway必威体育官网
当前位置:首页 > IT技术

Java中关于nextInt()、next()和nextLine()

时间:2019-10-06 16:14:31来源:IT技术作者:seo实验室小编阅读:75次「手机版」
 

nextint

博客地址:https://www.cnblogs.com/Skyar/p/5892825.html

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"或者空格之后的数据)。

相关阅读

论广告在用户运营中的简单作用

最近,“999感冒灵”的这则号称2017年度最走心的广告貌似占领了朋友圈、微博等各大社交媒体,很多人在讨论着、转发着。同样的还有,双

在财务系统中,进销项的发票管理怎么做

进销项发票如何管理?财务系统进销项发票管理是如何操作的?企业逐步扩大,业务随之拓展,进销项发票集中管控的需求越来越急切,因此我们财

获取YML文件中的值

yml文件 web: uploadPath: ${web.upload_path} platformUrl: ${web.platform_url} 在代码中通过@Value使用yml中给的值 @

如何调整Typora中的图片大小

今天用 Typora 记笔记。 插入了一个图片。挖槽了呢,图片默认宽度 100%。太大了。 直接使用 菜单栏的插入图片就是个坑~! 好在 MD

C++ 中 ZeroMemory、memset 危险需慎用

使用C/C++编程时,常使用ZeroMemory、memset或 “={0}”来对结构体对象进行初始化或清零。然而这三种方式都有各自的特点,使用时需谨

分享到:

栏目导航

推荐阅读

热门阅读