Seezy
Seezy

Reputation: 15

Android Separating two numbers with comma

At this moment my code separating like this 1,2,1,2,1,2,2,2,1 and i want to make this 11,22,12,21,11,11,11

my code:

public void onClick(View arg0) {

     ArrayList<String> list = new ArrayList<String>();

    switch(arg0.getId()){
    case R.id.one:
        //disp.append("1");

         list.add("1");

        break;
        case R.id.two:
            list.add("2");

    }

    StringBuilder sb = new StringBuilder();
    for (String s : list) {
           sb.append(s);
           if (sb.length() > 0)
                 sb.append(",");
    }
    String returnedItems = sb.toString();
    System.out.println(returnedItems);
    disp.append(returnedItems);


}

any idea and help, im new in java and programming

Upvotes: 0

Views: 337

Answers (1)

Jason C
Jason C

Reputation: 40325

Instead of using the for (String s:list) syntax, you can loop by index:

for (int n = 0; n < list.size(); ++ n) {
   String s = list.get(n);
   sb.append(s);
   ...
}

Now you have the index of the element available, and you can use that to determine when to insert commas, e.g.:

for (int n = 0; n < list.size(); ++ n) {
   String s = list.get(n);
   sb.append(s); 
   if (n % 2 == 1) // append a comma after odd elements
      sb.append(",");
}

Reworking that to keep the string from ending with a stray "," if list contains an even number of elements is left as an exercise (hint: think about inserting commas before even elements instead of after odd ones).

Upvotes: 1

Related Questions