关于方法接受多个输入的Java String问题

huangapple go评论88阅读模式
英文:

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!"

huangapple
  • 本文由 发表于 2020年7月30日 09:27:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/63164816.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定