了解Scanner的nextLine(),next()和nextInt()方法 [英] Understanding Scanner's nextLine(), next(), and nextInt() methods

查看:180
本文介绍了了解Scanner的nextLine(),next()和nextInt()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解这三种方法的工作原理。以下是我理解它们的方法:

I am trying to understand how these three methods work. Here's how I understood them:


  • nextLine()读取当前的剩余部分即使它是空的也行。

  • nextInt()读取整数,但不读取转义序列\ n。

  • next()读取当前行但不读取\ n。

  • nextLine() reads the remainder of the current line even if it is empty.
  • nextInt() reads an integer but does not read the escape sequence "\n".
  • next() reads the current line but does not read the "\n".

假设我有以下代码:

import java.util.Scanner;

public class Welcome2
{
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Next enter two words:");

        int n; 
        String s1, s2; 

        n = keyboard.nextInt(); 
        s1 = keyboard.next(); 
        s2 =  keyboard.nextLine(); 
        System.out.println(" n is " + n + " s1 is " + s1 + " s2 is " + s2); 
    }
}

如果我输入的是:

2 

Hi 

Hello 

然后我在屏幕上得到以下输出:

Then I get the following output on screen:

n is 2 
s1 is hi 
s2 is  

为什么 s1 的值为HI?

这是否意味着方法 next()读取下一行,即使第一行的转义符也是如此还没有被 nextInt()读取?

Does this mean that the method next() reads the next line even though the escape character for the first line has not been read by nextInt()?

推荐答案


nextLine()读取当前行的剩余部分,即使它是空的。

nextLine() reads the remainder of the current line even if it is empty.

正确。


nextInt()读取整数但不读取转义序列\ n。

nextInt() reads an integer but does not read the escape sequence "\n".

更正 1


next()读取当前行但不读取\ n。

next() reads the current line but does not read the "\n".

不正确。实际上, next() 方法读取下一个完整令牌。这可能是也可能不是当前行的其余部分。它可能会或可能不会消耗终点,具体取决于行尾的位置。 javadoc描述了精确的行为,你可能需要仔细阅读它,以便你能完全理解细微差别。

Incorrect. In fact, the next() method reads the next complete token. That may or may not be the rest of the current line. And it may, or may not consume an end-of line, depending on where the end-of-line is. The precise behavior is described by the javadoc, and you probably need to read it carefully for yourself in order that you can fully understand the nuances.

所以,在你的例子中:

So, in your example:


  1. nextInt()调用消耗 2 字符并离开位于 NL

next()调用会跳过 NL ,消耗 H i ,并将光标留在第二个NL。

The next() call skips the NL, consumes H and i, and leaves the cursor at the second NL.

nextLine()调用消耗第二行的其余部分;即 NL

The nextLine() call consumes the rest of the 2nd line; i.e. the NL.






1 ...除了您的术语错误。在读取数据时,它不是转义序列。它是一个行尾序列,可能包含CR,NL或CR NL,具体取决于平台。您正在谈论的转义序列是Java源代码,字符串和字符文字。它们可以>>代表<< CR或NL或......其他字符。

这篇关于了解Scanner的nextLine(),next()和nextInt()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆