Reputation: 11
There are two for loops and I want to increment array list value that is of string type by one from inner for loop. How I can do that?
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;
}
}
Upvotes: 0
Views: 1485
Reputation: 2629
Order to do that incrementation you have to change the algorithm by inserting a String to floating point conversion steps (I assume that distances are represented as floating points with in the 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;
}
}
Upvotes: 1
Reputation: 140
String can't be incremented. So instead of passing strDist
string to PrintStream
you can parse the string to an Integer
and do something like this:
System.out.printf("For Location : %s, Zip code 30303. Distance in Miles: %d%n", strloc, Integer.valueOf(strDist) + 1);
Upvotes: 2
Reputation: 377
Arraylists can hold a list of Object so you can't iterate through it with the type String.
After fixing this, the strDist will still not proceed to the next iteration this is because of the break statement, remove it.
You can do something like the following:
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
}
Upvotes: 0
Reputation: 41
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;
}
}
Hope it helps!
Upvotes: 3