如何将arraylist String值增加一个

时间:2017-12-27 10:10:59

标签: java arrays arraylist

有两个for循环,我想从inner for循环增加一个字符串类型的数组列表值。我怎么能这样做?

ArrayList<String> location; //Location and distanceInMiles are ArrayList<String> type and i have store some value into it. 
ArrayList<String> distanceInMiles;
for(String strloc : location){
    for(String strDist : distanceInMiles){
        System.out.println("For Location :" + strloc + "Zip code 30303" + "Distance in Miles:" + strDist);// After print the value i want to increment strDist value by one
        break;
    }
}

4 个答案:

答案 0 :(得分:3)

    ArrayList<String> location; //Location and distanceInMiles are ArrayList<String> type and i have store some value into it.
    ArrayList<String> distanceInMiles;
    for(String strloc : location){
        ArrayList<String> clone = (ArrayList<String>) distanceInMiles.clone();
        distanceInMiles.clear();
        for(String strDist : clone){
            System.out.println("For Location :" + strloc + "Zip code 30303" + "Distance in Miles:" + strDist);// After print the value i want to increment strDist value by one
            distanceInMiles.add(Integer.parseInt(strDist) + 1 + "");
            break;
        }
    }

希望它有所帮助!

答案 1 :(得分:2)

字符串不能递增。因此,不是将strDist字符串传递给PrintStream,而是将字符串解析为Integer,并执行以下操作:

System.out.printf("For Location : %s, Zip code 30303. Distance in Miles: %d%n", strloc, Integer.valueOf(strDist) + 1);

答案 2 :(得分:1)

为了做到这种增量,你必须通过将一个String插入到浮点转换步骤来改变算法(我假设距离在字符串中表示为浮点)。

List<String> location; 
List<String> distanceInMiles;

for(String strloc : location){
   for(int i=0; i < distanceInMiles.size(); i++){
       String strDist = distanceInMiles.get(i);
       System.out.println("For Location :" + strloc + "Zip code 30303" + "Distance in Miles:" + strDist);
       double value = Double.parseDouble(strDist);
       value++;
       distanceInMiles.set(i, String.valueOf(value));
       break;
   }
}

答案 3 :(得分:0)

Arraylists可以保存Object列表,因此您无法使用String类型迭代它。

修复此问题后,strDist仍然不会进行下一次迭代,这是因为break语句,将其删除。

您可以执行以下操作:

for (Object strDist : distanceInMiles) {

            System.out.println("For Location :" +strloc+ "Zip code 30303" + "Distance in Miles:" + strDist);// After print the value i want to increment strDist value by one

             // remove break
        }