将数组的索引0与1、2与3、4与5组合 [英] Combining an array's index 0 with 1, 2 with 3, 4 with 5

查看:48
本文介绍了将数组的索引0与1、2与3、4与5组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,在一个数组中

  [ 1, 2, 3, 4,  5, 6, 7] 

我希望代码产生输出

  [ 1 2, 3 4, 5 6, 7] 

到目前为止,我有:

  public static void Combine(ArrayList< String> list){
for(int i = 0; i< list.size(); i ++){
字符串a0 = list.get(i );
字符串a1 = list.get(i + 1);
字符串a2 = a0 + a1;
if(list.get(i + 1)== null){
a2 = a1;
}
list.remove(i);
list.remove(i + 1);
list.add(i,a2);
}
}


解决方案

您的当前代码将抛出 OutOfBoundsException ,因为它不会在循环时检查列表是否在索引中包含值。



  public static ArrayList< String>>执行此操作的一种好方法是初始化一个将保存连接值的列表。

Combine(ArrayList< String> list){
ArrayList< String> newList =新的ArrayList<>();

for(int i = 0; i< list.size(); i = i + 2){
//获取第一个数字
字符串firstNumber = list.get (一世);

//检查第二个数字是否存在
if(i + 1 字符串secondNumber = list.get(i + 1);
//将连接的字符串添加到新列表
newList.add(firstNumber + + secondNumber);
} else {
//不存在第二个数字,添加剩余的数字
newList.add(firstNumber);
}
}

return newList;
}


For example, in an array

["1", "2", "3", "4", "5", "6", "7"]

I want the code to produce an output of

["1 2", "3 4", "5 6", "7"]

What I have so far:

public static void combine(ArrayList<String> list) {
    for (int i = 0; i < list.size(); i++) {
            String a0 = list.get(i);
            String a1 = list.get(i + 1);
            String a2 = a0 + a1;
            if (list.get(i + 1) == null) {
                a2 = a1;
            }
            list.remove(i);
            list.remove(i + 1);
            list.add(i, a2);    
    }
}

解决方案

Your current code will throw an OutOfBoundsException because it is not checking if the list holds a value in the index while looping.

A good way to do that is to initialize a list that will hold the concatenated values.

public static ArrayList<String> combine(ArrayList<String> list) {
    ArrayList<String> newList = new ArrayList<>();

    for (int i = 0; i < list.size(); i = i + 2) {
        // get first number
        String firstNumber = list.get(i);

        // check if second number exists
        if (i + 1 < list.size()) {
            String secondNumber = list.get(i + 1);
            // add concatenated string to new list
            newList.add(firstNumber + " " + secondNumber);
        } else {
            // no second number exists, add the remaining number
            newList.add(firstNumber);
        }
    }

    return newList;
}

这篇关于将数组的索引0与1、2与3、4与5组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆