java - 在循环中累积字符串并打印出所有字符串

标签 java string

我试图弄清楚如何在 for 循环中累积用户输入,然后使用一个 system.out.print 将它们打印出来。这是我针对该问题的测试代码。 因此,例如,如果用户输入:Mike 作为他的名字,Joe、Jack、Dave 作为其他名字,如何仅使用一个变量来打印它们,因为变量的数量是未知的,因为用户做出了这一决定。是否可以在没有字符串生成器和数组的情况下做到这一点?

import java.util.Scanner;
public class Accumulate {

public static void main(String[] args) {
String othernames = " ",name;
int count,n;
Scanner kybrd = new Scanner(System.in);
System.out.println("Enter your name ");
name = kybrd.nextLine();
System.out.println("How many other names would you like to add ? ");
count = kybrd.nextInt();
kybrd.nextLine();

for(n=0;n<count;++n){

System.out.println("Enter other names ");
othernames = kybrd.nextLine();



}

System.out.println("Other names are "+othernames + " And your name is "+ name);

}

}

最佳答案

您可以递归调用它,例如:

Scanner sc = new Scanner(System.in);
String s;
while(condition) {
    s = s + sc.nextLine();
}

这将始终连接您输入的行,您还可以添加逗号、空格或任何您想要添加的内容。

关于java - 在循环中累积字符串并打印出所有字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29786619/

相关文章:

java - 使用 springs RESTtemplate 检索 Jsonobjects 列表时出现异常

java - 阻止除一个组件之外的整个 swing ui - "dialog style"

java - 记录用户交互 : log4j?

java - 在 C++ 与 Java 中利用对象的巨大 vector (或数组?)的最快方法

java - 为什么 list.get(0).equals(null) 不起作用?

c++ - 将字符串对象与 C++ 中的字符串文字进行比较 : why no compile errors?

python - 字符串被突变为字典但无法弄清楚在哪里

c++ - 将对象格式化为字符串

c++ - 循环遍历 Char 数组 - 拆分成单独的字符串 - Arduino

python - python 中的交错字符串