0
`while (sc.hasNext()) {
                    System.out.println("Inside second while");
                    String data =br.readLine();
                    System.out.println("Scanning");
                    if (index == 0)
                        ud1.setUserId(Integer.parseInt(data));
                    else if (index == 1)
                        ud1.setUserName(data);
                    else if (index == 2)
                        ud1.setUserAddress(data);
                        else if (index == 3){
                        ud1.setUserEmail(data);
                    break;
                    }
                    else{
                        System.out.println("invalid data::" + data);
                    }
                    index++;
                }
                index = 0;
                ud.add(ud1);
                System.out.println(ud);`

Here i have used setters. Now how should i use getter to retrieve the data of arraylist. Please help me with the for each loop using getters

1 Answers1

0

Assuming that you have different 'UserData' - Objects in your ArrayList ud (It would be helpful to include this and remove less relevant info like the "invalid data" from your code snippet) and you want to write them into a StringBuilder sb = ... that will be exported into a CSV-file, you should:

  1. Write the CSV Header, if required, in the desired order:

    sb.append("ID;Name;Address;Email\n");
    
  2. Iterate over the ArrayList:

    for(UserData data : ud){
        sb.append(data.getUserID()).append(";");
        // append other entries
        sb.append(data.getUserEmail()).append("\n");
    }
    
  3. Write the contents of the StringBuilder to a csv-file. Information on writing files can be found here: How do I create a file and write to it in Java? or in more detail here: https://docs.oracle.com/javase/tutorial/essential/io/file.html

However, using a UserData - object with getters and setters seems to be impractical to be: it would be easier to store the input in an ArrayList<String> and iterate them in a nested for-loop.

LyteFM
  • 895
  • 8
  • 12