1

I've declared two ArrayLists and one array which name is str. I want to store even indexed elements of array in number ArrayList and odd indexed in name ArrayList.

Please help me. Thank you.

 import java.util.Scanner;
 import java.util.*;

 public class Que1 {

  public static void main(String[] args) 
  {

   int a=0;
   String[] str=new String[1000];

   List<String> name = new ArrayList<>();
   List<Integer> number = new ArrayList<>();

   Scanner sc=new Scanner(System.in);
   a=sc.nextInt();


   for(int i=0;i<=a;i++)
      {
         String ns=sc.nextLine();
         str=ns.split(" ");  
            for(int j=0;j<str.length;j=j+2)
                {
                     name.add(str[j]);
                     Collections.sort(name);
                }

            for(int k=1;k<str.length;k=k+2)
                 {
                     int add=Integer.parseInt(str[k]);
                     number.add(add);
                     Collections.sort(number);
                 }
      }

   for(int i=0;i<str.length;i++)
      {            
            String valueName = name.get(i);
            String valueNumber = number.get(i).toString();
            System.out.print(valueName+ " ");
            System.out.print(valueNumber+ " ");
      }      
  }
}

output:: here number Arraylist is first printing rather than name ArrayList and In name arrayList one white space also print i don't know why and last element of name ArrayList is also not printing. can anyone find solution

2
a 11 b 22 c 33
d 44 e 55 f 66
  11 a 22 b 33 c 44 d 55 e 66 BUILD SUCCESSFUL (total time: 20 seconds)

2 Answers2

1

You are trying to retrieve the item in the size place but since the counting of items starts from 0, the last item is at size() - 1.

Meaning, you for should write it like this:

for (int i = 0; i < name.size(); i++)
Idos
  • 15,053
  • 14
  • 60
  • 75
Tzach Solomon
  • 688
  • 8
  • 27
1

You can write:

for(int j=0; j != str.length; j++) {
    if (j % 2 == 0) { // Even
        number.add(str[j]); 
    } else { // Odd
        name.add(str[j]);
    }
}

And to print the arrays replace the <= with <

Marco Santarossa
  • 4,058
  • 1
  • 29
  • 49