使用子方法将字符串加倍

时间:2018-09-30 23:49:48

标签: arrays string list

如何编写称为doubleList的静态方法,该方法将ArrayList中的Strings作为形式参数,并用相同的String中的两个替换每个String?

例如,如果列表在调用方法之前存储了值["how", "are", "you"],则应在方法执行完之后存储值["how", "how", "are", "are", "you", "you"]

public static void main(String[] args) throws IOException 
{
   ArrayList<String> x = new ArrayList<>();  
    x.add("how");
    x.add("are");
    x.add("you");
    System.out.println(x);
    doubleList(x);
    System.out.println(x);


    public static void doubleList(ArrayList<String> list, String t) 
{

}

2 个答案:

答案 0 :(得分:1)

尝试一下:

public class MyReplicatingClass {

    private static ArrayList<String> arrayList;

    public static void main(String[] args) {
        arrayList = new ArrayList<>();
        arrayList.add("how");
        arrayList.add("are");
        arrayList.add("you");

        System.out.println(arrayList);
        doubleList(arrayList);
        System.out.println(arrayList);
    }

    private static void doubleList(ArrayList<String> list) {
        ArrayList<String> tmpList = new ArrayList<>();

        for (String element : list) {
            int numOfRepeats = 2; // can be changed to 3 -> [how, how, how, ...]
            while (numOfRepeats > 0) {
                tmpList.add(element);
                numOfRepeats--;
            }
        }

        arrayList = new ArrayList<>(tmpList);
    }
}

如上所述,可以自定义。这是重复6的输出:

[how, are, you]
[how, how, how, how, how, how, are, are, are, are, are, are, you, you, you, you, you, you]

答案 1 :(得分:0)

GET /flight/123/status

输入[“如何”,“是”,“您”?

输出[如何,如何,是?,你?]