gpt4 book ai didi

java - 我如何使用扫描仪从键盘读取一系列字符串,全部在一行上,并将它们连接起来

转载 作者:行者123 更新时间:2023-11-29 09:10:36 27 4
gpt4 key购买 nike

我如何使用 Scanner 从键盘读取一系列字符串,全部在一行上,并将它们连接起来。

这是我目前的代码:

import java.util.Scanner;

public class Exam12Practice {

public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
String words="";
System.out.println("enter a word");
while(input.hasNext())
{
words = words.concat(input.next());
}

System.out.println(words);
}
}

最佳答案

您的代码已经完成了您的要求。让它工作

Type in your words
Press Enter
Press CTRL-Z (^D on *nix systems)

注意事项:

input.hasNext() 将始终为 STDIN 返回 true,因此仅按 Enter 本身是行不通的。

您可以使用 input.readLine() 并拆分单词进行练习。

大多数人可能更喜欢使用 StringBuilder,因为它提供的性能优于 String.concat

关于java - 我如何使用扫描仪从键盘读取一系列字符串,全部在一行上,并将它们连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12665835/

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