gpt4 book ai didi

java - 如何在 Java 中获取 StringBuffer 对象的输入?

转载 作者:行者123 更新时间:2023-12-02 05:15:41 24 4
gpt4 key购买 nike

例如,我们可以接受 String 类的对象作为以下代码中的输入。如何对 StringBuffer 类执行相同操作?

String a = new String();
Scanner in = new Scanner(System.in);
System.out.println("Enter a String");
a=in.nextLine();

最佳答案

代码:

StringBuffer sbuffer = new StringBuffer();
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
sbuffer.append(input.nextLine());

会将您的“下一行”添加到 StringBuffer sbuffer。

这是因为 input.nextLine() 返回一个 String,而 sbuffer.append(...) 接受各种参数,包括String

StringBuffer 的文档可以在 this Java page 找到。 .

同样,scanner documentation也可用。

这些链接提供了每个类可用的方法列表,以及方法可以采用的参数/参数。 Java 文档经常提供用例示例。

摘自StringBuffer文档的开头段落:

A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

关于java - 如何在 Java 中获取 StringBuffer 对象的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26965931/

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