My aim is to fill a 3x3 grid of Jtextfield in java swing with values and position of entry in that grid sourced from a text file.I made a file named aa.txt. Its contents are:-

a1-3
b3-9
c2-4

a1,b3,c2,... are names of textfields in grid and numbers separated by hyphen are the values i need to enter in the respective field.
I wrote a code for that but it is not working as expected. Instead of going through all the entries in text file, the code is just filling data into first box for entry i.e a1 only gets filled and rest of them are not filled.
There is no syntatical error(or ArrayOutOfBounds exception); the only error is i cannot get the desired result.

File f= new File("C:\\Users\\Utkarsh\\Desktop\\aa.txt");
    String[] posval=new String[5];int c=0;
    Scanner s= new Scanner(f);
    while(s.hasNext()){
        posval[c]=s.nextLine();
        c++;
    }
    String[] pos= new String[5];
    String[] val= new String[5];
    for(int j=0;j<3;j++){
        String[] temp=posval[j].split("-");
        pos[j]= temp[0];
        val[j]=temp[1];
    }
    JTextField[][] a={{a1,a2,a3},{b1,b2,b3},{c1,c2,c3}};
    String[][] d={{"a1","a2","a3"},{"b1","b2","b3"},{"c1","c2","c3"}};
        for(int i=0;i<3;i++){
           for(int j=0;j<3;j++){
               if(pos[j].equals(d[i][j])){
                   a[i][j].setText(""+val[j]);
               }
           }
        }

Please tell me where i am going wrong. Thanks.
If u have a better algorithm to do the task, please tell me about it.

if(pos[j].equals(d[i][j]))

The value of j determines which of a1, a2, or a3 you get when i==0. And j also determines which line of the input file you are on. It seems like you don't really want to use it for both purposes, so it is probably accidental. Notice especially that b3-9 will be ignored unless it is the 3rd line, because that is the only line where j==2.

Aside from that issue, you really should avoid things like a1, a2, a3. The way you have to setup those arrays just proves that you should have been using arrays from the beginning. a1 should have been a[0] because it makes everything easier.

It would be simpler to convert the position references directly to array indexes -
eg
pos.charAt(0) - 'a' returns 0 if pos starts with 'a', 1 for 'b', 2 for 'c'
and
pos.charAt(1) - '1'similarly for the numeric part.
Now you have the i,j values to index the array of text fields directly

commented: Exactly what I was thinking ;-) +13
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.