我试图弄清楚如何在 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/