gpt4 book ai didi

java - nextLine() 方法如何工作

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:53 26 4
gpt4 key购买 nike

考虑代码:

import java.util.*;

public class TestClass
{
public static void main(String[] args)
{
Scanner input= new Scanner ("34\n567");

while(input.hasNext())
{
System.out.println(input.nextLine());
}

input.close();
}
}

我得到的输出:

34
567

当我尝试通过 nextLine() 读取字符串时,它不应该像这样读取它,因为它必须仅在行分隔符处终止,而 \n 不是 Java 中的行分隔符。

那么这是怎么发生的呢?

最佳答案

试试这个

    String s = "a\r\nb";
for (String str : s.split(System.getProperty("line.separator"))) {
System.out.println(str);
}
System.out.println("Length:"+s.split(System.getProperty("line.separator")).length);

\r\n 代表新行。

输出

 a
b
Length:2

关于java - nextLine() 方法如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22887446/

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