英文:
Java String... question regarding multiple inputs for a method
问题
可以创建一个类,并拥有一个名为String ... 的属性,它可以接受任意数量的字符串,无论多少都可以。
示例:
请原谅我的粗略伪代码,这是针对Java的。
// 这是方法:
public void getXXXX(String ...) {
// 随机代码在循环中执行,输入的字符串数量可以随意
}
// 这是调用它的代码
getXXXX("Benjamin", "Jordan", "Steve")
getXXXX("Pengu", "No")
getXXXX("hi")
英文:
is it possible to create a class and have a String ... attribute that takes as many or as little strings as you put?
example:
please excuse my rough pseudocode, this is for java.
//this is the method:
public void getXXXX(String ...) {
//random code executes in a loop with as many as strings that are inputted
}
//this code calls it
getXXXX("Benjamin","Jordan","Steve")
getXXXX("Pengu","No")
getXXXX("hi")
答案1
得分: 2
是的,你输入的基本上可以工作,你只需要在类型后面添加一个参数名称。
class StringDecorator {
public static String join(final String... strings) {
final var builder = new StringBuilder();
for (final var string : strings) {
builder.append(string);
}
return builder.toString();
}
}
然后在某个地方调用它:
StringDecorator.join("Hello, ", "World!"); // "Hello, World!"
英文:
Yes, what you entered will more or less work, you just need a parameter name after your type.
class StringDecorator {
public static String join(final String... strings) {
final var builder = new StringBuilder();
for (final var string : strings) {
builder.append(string);
}
return builder.toString();
}
}
Then invoke this somewhere
StringDecorator.join("Hello, ", "World!"); // "Hello, World!"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论