栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

nextInt(),nextLine(),next()方法的区别

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

nextInt(),nextLine(),next()方法的区别

用Java刷算法题的小伙伴对于严格ACM模式下,你的代码需要处理输入输出,这点数据初始化输入可能就让有些小伙伴苦不堪言,经常出现写了next***()函数但是变量并没有获取到,因此总结一下常用的输入函数的用法,以及他们的区别。

理论

nextInt():

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

仅仅读取int类型的变量,nextInt()函数在输入读取完后,将光标放在同一行。
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.

读取输入内容,包括两个单词中间的空格,换句话说读取的内容直到遇见’n’符号,当使用nextLine()函数读取完毕后,将光标位置置于下一行。
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.

读取输入的内容直到遇见空格,它不能读取两个被空格分开的字符,next()函数读取完后,也是将光标放在同一行。

实践1
import java.util.Scanner;

public class Main {
    public static void main(String []args){
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        while (n > 0) {
            String str = scanner.nextLine();
            System.out.println("str的值是:"+str);
            n--;
        }

    }
}

测试1:

输入2,回车,helloword

结果:

2
str的值是:
helloworld
str的值是:helloworld

解析

1、nextInt()读取2的内容,并将光标移动到2和helloworld之间
2、nextLine()读取一行的内容n(实际回车,但是回车不显示),并将光标移动到下一行
3、nextLine()读取helloworldn(实际是内容加回车,但是回车不显示)

测试2:

输入2,空格,helloworld,空格,test,回车

结果:

2 helloworld test
str的值是: helloworld test
hello
str的值是:hello

解析

1、nextInt()读取2的内容,并将光标移动到2和helloworld之间
2、nextLine()读取一行的内容 helloworld testn(实际是空格加内容加回车,但是回车不显示),可以读取到之间的空格,并将光标移动到下一行
3、nextLine()读取hellon(实际是内容加回车,但是回车不显示)
实践2
import java.util.Scanner;

public class Main {
    public static void main(String []args){
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        while (n > 0) {
            String str = scanner.next();
            System.out.println("str的值是:"+str);
            n--;
        }

    }
}

测试1:

输入2,回车,hello,回车,world,回车

结果:

2
hello
str的值是:hello
world
str的值是:world

解析:

1、nextInt()读取2的内容,并将光标移动到2和n回车之间
2、next()读取光标后面的内容nhello(实际回车+hello),但是next()不能读取回车或空格,并且遇到下一个回车或者空格就会停止,因此得到hello
3、next()读取光标后面的内容nworld(实际回车+world),但是next()不能读取回车或空格,并且遇到下一个回车或者空格就会停止,因此得到world

测试2:

输入2,空格,hello,空格,world,回车

结果:

2 hello world
str的值是:hello
str的值是:world

解析:

1、nextInt()读取2的内容,并将光标移动到2和第一个空格之间。
2、next()读取光标后面的内容 hello(实际空格+hello),但是next()不能读取回车或空格,并且遇到下一个回车或者空格就会停止,因此得到hello,并将光标移动到hello与第二个空格之间。
3、next()读取光标后面的内容 world(实际空格+world),但是next()不能读取回车或空格,并且遇到下一个回车或者空格就会停止,因此得到world,并将光标移动到结尾。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/325217.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号