Java Scanner 类中的 next() 和 nextLine() 方法有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22458575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:50:21  来源:igfitidea点击:

What's the difference between next() and nextLine() methods from Scanner class?

javajava.util.scanner

提问by AnnieOK

What is the main difference between next()and nextLine()?
My main goal is to read the all text using a Scannerwhich may be "connected" to any source(file for example).

next()和之间的主要区别是nextLine()什么?
我的主要目标是使用Scanner可以“连接”到任何源(例如文件)的a 读取所有文本。

Which one should I choose and why?

我应该选择哪一个,为什么?

采纳答案by Tristan

I always prefer to read input using nextLine()and then parse the string.

我总是喜欢使用读取输入nextLine()然后解析字符串。

Using next()will only return what comes before the delimiter (defaults to whitespace). nextLine()automatically moves the scanner down after returning the current line.

Usingnext()只会返回分隔符之前的内容(默认为空格)。nextLine()返回当前行后自动向下移动扫描仪。

A useful tool for parsing data from nextLine()would be str.split("\\s+").

解析数据的有用工具nextLine()str.split("\\s+").

String data = scanner.nextLine();
String[] pieces = data.split("\s+");
// Parse the pieces

For more information regarding the Scanner class or String class refer to the following links.

有关 Scanner 类或 String 类的更多信息,请参阅以下链接。

Scanner: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

扫描仪:http: //docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

String: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

字符串:http: //docs.oracle.com/javase/7/docs/api/java/lang/String.html

回答by RKC

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

next()只能读取输入直到空格。它无法读取由空格分隔的两个单词。此外,next()在读取输入后将光标置于同一行。

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.

nextLine()读取输入,包括单词之间的空格(即,它读取到行尾\n)。读取输入后,nextLine()将光标定位在下一行。

For reading the entire line you can use nextLine().

要阅读整行,您可以使用nextLine().

回答by onesixtyfourth

From javadocs

来自javadocs

next() Returns the next token if it matches the pattern constructed from the specified string. nextLine() Advances this scanner past the current line and returns the input that was skipped.

next() 如果下一个标记与从指定字符串构造的模式匹配,则返回下一个标记。nextLine() 将此扫描器前进到当前行并返回被跳过的输入。

Which one you choose depends which suits your needs best. If it were me reading a whole file I would go for nextLine until I had all the file.

您选择哪一个取决于哪一个最适合您的需求。如果是我阅读整个文件,我会选择 nextLine 直到我拥有所有文件。

回答by Foobar

From the documentation for Scanner:

来自Scanner的文档:

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

Scanner 使用分隔符模式将其输入分解为标记,默认情况下与空格匹配。

From the documentation for next():

next()的文档中:

A complete token is preceded and followed by input that matches the delimiter pattern.

一个完整的标记前后是与分隔符模式匹配的输入。

回答by Oleg Sklyar

From JavaDoc:

来自 JavaDoc:

  • A Scannerbreaks its input into tokens using a delimiter pattern, which by default matches whitespace.
  • next(): Finds and returns the next complete token from this scanner.
  • nextLine(): Advances this scanner past the current line and returns the input that was skipped.
  • AScanner使用分隔符模式将其输入分解为标记,默认情况下与空格匹配。
  • next():从这个扫描器中查找并返回下一个完整的令牌。
  • nextLine(): 将此扫描器推进到当前行并返回被跳过的输入。

So in case of "small example<eol>text"next()should return "small" and nextLine()should return "small example"

所以在"small example<eol>text"next()应该返回“小”的情况下,应该nextLine()返回“小例子”

回答by Musaddique

next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...

next() 和 nextLine() 方法与 Scanner 相关联,用于获取字符串输入。他们的区别是...

next() can 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() 只能读取输入直到空格。它无法读取由空格分隔的两个单词。此外,next() 在读取输入后将光标置于同一行。

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.

nextLine() 读取输入,包括单词之间的空格(即,它读取到行尾 \n)。读取输入后,nextLine() 将光标定位在下一行。

import java.util.Scanner;

public class temp
{
    public static void main(String arg[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("enter string for c");
        String c=sc.next();
        System.out.println("c is "+c);
        System.out.println("enter string for d");
        String d=sc.next();
        System.out.println("d is "+d);
    }
}

Output:

输出:

enter string for c abc def
c is abc

输入字符串为 c abc def
c 是 abc

enter string for d

输入字符串 d

d is def

d 是定义

If you use nextLine() instead of next() then

如果你使用 nextLine() 而不是 next() 那么

Output:

输出:

enter string for c

为 c 输入字符串

ABC DEF
c is ABC DEF
enter string for d

ABC DEF
c 是 ABC DEF
输入字符串为 d

GHI
d is GHI

GHI
d 是 GHI

回答by murali krish

What I have noticed apart from next() scans only upto space where as nextLine() scans the entire line is that next waits till it gets a complete tokenwhere as nextLine() does not wait for complete token, when ever '\n' is obtained(i.e when you press enter key) the scanner cursor moves to the next line and returns the previous line skipped.It does not check for the whether you have given complete input or not, even it will take an empty string where as next() does not take empty string

我注意到除了 next() 只扫描到空间,其中 nextLine() 扫描整行是next 等待直到它获得完整的令牌,而nextLine() 不等待完整的令牌,无论何时 '\n'获得(即当您按下回车键时)扫描仪光标移动到下一行并返回跳过的前一行。它不会检查您是否提供了完整的输入,即使它会采用空字符串,而 next() 不会采用空字符串

public class ScannerTest {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int cases = sc.nextInt();
        String []str = new String[cases];
        for(int i=0;i<cases;i++){
            str[i]=sc.next();
        }
     }

}

Try this program by changing the next() and nextLine() in for loop, go on pressing '\n' that is enter key without any input, you can find that using nextLine() method it terminatesafter pressing given number of cases where as next() doesnot terminateuntill you provide and input to it for the given number of cases.

通过更改 for 循环中的 next() 和 nextLine() 来尝试这个程序,继续按 '\n' 是没有任何输入的回车键,你会发现使用nextLine() 方法它在按下给定数量的情况后终止因为next() 不会终止,直到您为给定数量的案例提供并输入它。

回答by himani1349

In short: if you are inputting a string array of length t, then Scanner#nextLine() expects t lines, each entry in the string array is differentiated from the other by enter key.And Scanner#next() will keep taking inputs till you press enter but stores string(word) inside the array, which is separated by whitespace.

简而言之:如果你输入一个长度为 t 的字符串数组,那么 Scanner#nextLine() 需要 t 行,字符串数组中的每个条目都通过回车键与其他条目区分开来。并且 Scanner#next() 将继续输入直到您按 Enter 但将 string(word) 存储在数组中,该数组由空格分隔。

Lets have a look at following snippet of code

让我们看看下面的代码片段

    Scanner in = new Scanner(System.in);
    int t = in.nextInt();
    String[] s = new String[t];

    for (int i = 0; i < t; i++) {
        s[i] = in.next();
    }

when I run above snippet of code in my IDE (lets say for string length 2),it does not matter whether I enter my string as

当我在我的 IDE 中运行上面的代码片段时(假设字符串长度为 2),我是否输入我的字符串并不重要

Input as :- abcd abcd or

输入为:- abcd abcd 或

Input as :-

输入为:-

abcd

A B C D

abcd

A B C D

Output will be like abcd

输出将像 abcd

abcd

A B C D

But if in same code we replace next() method by nextLine()

但是如果在相同的代码中我们用 nextLine() 替换 next() 方法

    Scanner in = new Scanner(System.in);
    int t = in.nextInt();
    String[] s = new String[t];

    for (int i = 0; i < t; i++) {
        s[i] = in.nextLine();
    }

Then if you enter input on prompt as - abcd abcd

然后,如果您在提示符下输入输入 - abcd abcd

Output is :-

输出是:-

abcd abcd

abcd abcd

and if you enter the input on prompt as abcd (and if you press enter to enter next abcd in another line, the input prompt will just exit and you will get the output)

如果您在提示中输入输入为 abcd(如果您按 Enter 键在另一行中输入下一个 abcd,则输入提示将退出,您将获得输出)

Output is:-

输出是:-

abcd

A B C D

回答by annoo9605

  • Just for another example of Scanner.next() and nextLine() is that like below : nextLine() does not let user type while next() makes Scanner wait and read the input.

     Scanner sc = new Scanner(System.in);
    
     do {
        System.out.println("The values on dice are :");
        for(int i = 0; i < n; i++) {
            System.out.println(ran.nextInt(6) + 1);
        }
        System.out.println("Continue : yes or no");
     } while(sc.next().equals("yes"));
    // while(sc.nextLine().equals("yes"));
    
  • 只是 Scanner.next() 和 nextLine() 的另一个例子如下: nextLine() 不允许用户输入,而 next() 使 Scanner 等待并读取输入。

     Scanner sc = new Scanner(System.in);
    
     do {
        System.out.println("The values on dice are :");
        for(int i = 0; i < n; i++) {
            System.out.println(ran.nextInt(6) + 1);
        }
        System.out.println("Continue : yes or no");
     } while(sc.next().equals("yes"));
    // while(sc.nextLine().equals("yes"));
    

回答by Z. Zhang

For this question, the key point is to find where the method will stop and where is the cursor after calling the methods. All methods will read information (does not include whitespace) between the cursor position and the next default delimiters(whitespace, tab, \n--created by pressing Enter) and the cursor stops before the delimiters, except for the nextLine(), which reads information (including whitespace created by delimiters) between the cursor position and \n and the cursor stops behind \n.

对于这个问题,关键是要找到方法会在哪里停止,调用方法后光标在哪里。所有方法都将读取光标位置和下一个默认分隔符(空格、制表符、\n--通过按 Enter 创建)之间的信息(不包括空格)并且光标停在分隔符之前,除了 nextLine(),它读取光标位置和 \n 之间的信息(包括由分隔符创建的空格),并且光标停在 \n 后面。

For example: ( | representing the current cursor position; _ representing whitespace; stream in Bold the information got by the calling method)

例如:( | 代表当前光标位置;_ 代表空格;以粗体流传输调用方法得到的信息)

23_24_25_26_27\n

23_24_25_26_27\n

Call nextInt(); read 23|_24_25_26_27\n

调用 nextInt(); 阅读23|_24_25_26_27\n

Call nextDouble(); read 23_24|_25_26_27\n

调用 nextDouble(); 阅读 23_ 24|_25_26_27\n

Call next(); read 23_24_25|_26_27\n

调用 next(); 阅读 23_24_ 25|_26_27\n

Call nextLine(); read 23_24_25_26_27\n|

调用 nextLine(); 阅读 23_24_25 _26_27\n|

After this, the method should be called depending on your requirement.

在此之后,应根据您的要求调用该方法。