Reputation: 21
I'm working with string value like this String result "aa,bb,cc,dd,ee"
.
And already split it into aa bb cc dd ee
with
qrList = result.getContents().toString().split("\\,");
List<String> resultToString= new ArrayList(Arrays.asList(qrList));
Then I create four ArrayLists.
ArrayList<String> strA = new ArrayList();
ArrayList<String> strB = new ArrayList();
ArrayList<String> strCD = new ArrayList();
ArrayList<String> strE = new ArrayList();
When I use this code below to store string into each new ArrayList
.
for(int count=0; count<resultToString.size(); count++){
//separate string to array list
if(count%5==0){
strA.add(resultToString.get(count));
}else if(count%5==1){
strB.add(resultToString.get(count));
}else if(count%5==2||count%5==3){
strCD.add(resultToString.get(count));
}else if(count==4){
strE.add(resultToString.get(count));
}
The correct result would be
It doesn't work because I only get the index value at 0
(strA stored aa).
What should I do to improve my code?
Upvotes: 1
Views: 90
Reputation: 346
Modulus operator describes the remainder of your equation. Let us show and explain an example:
As explained in this documentation, performing modulus between two values will only show you the remainder value. For e.g. 8 % 3 == 2
because 8 divided by 3 leaves a remainder of 2.
The reason your code is not showing your desired results is due to the usage of your modulus operator. Regarding improving your code, I can tell that all you wanted is to use the Array List index so as to add the string from the resultToString
Array List.
Therefore I would modify your loop in the following manner:
for(int count=0; count < resultToString.size(); count++) {
//separate string to array list
if (count == 0){
strA.add(resultToString.get(count));
} else if (count == 1){
strB.add(resultToString.get(count));
} else if (count == 2 || count == 3){
strCD.add(resultToString.get(count));
} else if (count == 4){
strE.add(resultToString.get(count));
}
}
An alternative is to loop directly on the resulting String[]
and use that relative counter in the for loop for e.g.
String[] qrList = results.getContent().toString().split("\\,");
for(int count = 0; count < qrList.length; count++) {
//each index represents the split string e.g
// [0] == "aa"
// [1] == "bb"
// [2] == "cc"
// [3] == "dd"
// [4] == "ee"
if (count == 0){
strA.add(qrList[count]);
} else if (count == 1){
strB.add(qrList[count]);
} else if (count == 2 || count == 3){
strCD.add(qrList[count]);
} else if (count == 4){
strE.add(qrList[count]);
}
}
Upvotes: 0
Reputation: 37404
Simply use startsWith
and add appropriate values to list
for(int count=0; count<resultToString.size(); count++){
//separate string to array list
String s = resultToString.get(count);
if(s.startsWith("a")){
strA.add(s);
}else if(s.startsWith("b")){
strB.add(s);
}else if(s.startsWith("c")||s.startsWith("d")){
strCD.add(s);
}else if(s.startsWith("e")){
strE.add(s);
}
}
Upvotes: 2