gpt4 book ai didi

java - 了解 Scanner 的 nextLine()、next() 和 nextInt() 方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:12:52 27 4
gpt4 key购买 nike

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

  • nextLine() 读取当前行的剩余部分,即使它是空的。
  • nextInt() 读取一个整数但不读取转义序列“\n”。
  • next() 读取当前行但不读取“\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

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

n is 2 
s1 is hi
s2 is

为什么 s1 的值为“HI”?

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

最佳答案

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".

正确1

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

不正确。事实上,next()方法读取下一个完整的标记。这可能是也可能不是当前行的其余部分。它可能会也可能不会消耗行尾,具体取决于行尾的位置。 javadoc 描述了准确的行为,您可能需要自己仔细阅读它才能完全理解其中的细微差别。

因此,在您的示例中:

  1. nextInt() 调用消耗了 2 字符并离开了 NL 的位置。

  2. next() 调用跳过 NL,使用 Hi,并将光标留在第二个 NL。

  3. nextLine() 调用消耗了第二行的剩余部分;即 NL


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

关于java - 了解 Scanner 的 nextLine()、next() 和 nextInt() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32798803/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com