jhamza
jhamza

Reputation: 21

adding multiple String values in arraylist at a single index and write on file

I am trying to store more than 1 String value at a single index in my arraylist. i try the folowing code but it cannot print the desired output.it only write A input on file only and donot B and C input

    List<String[]> arr = new ArrayList<String[]>(2);

    String A=jTextField1.getText();
    String B=jTextField2.getText();
    String C=jTextField3.getText();

    String[] element1 = new String[] {A,B,C};  /// A,B,C is an input String
    arr.add(element1);

    try{
        FileWriter f1=new FileWriter("test.txt",true);
        try(BufferedWriter out=new BufferedWriter(f1)){
            int sz=arr.size();
            for(int i=0;i<sz;i++){
                out.write(arr.get(0)[i].toString()+"\n");

            }
        }

Upvotes: 2

Views: 3180

Answers (3)

kaushik
kaushik

Reputation: 312

you are using arr.size() where arr is the arrayList. So, it will not be equal to the size of the string array. user the size of the String array. place

int sz=arr.get(0).length; instead of this. int sz=arr.size();

Upvotes: 0

Rodrigo Nogueira
Rodrigo Nogueira

Reputation: 161

you can do something like this:

arr.addAll(Arrays.asList(element1));

Upvotes: 0

Sudharsan Selvaraj
Sudharsan Selvaraj

Reputation: 4832

you are using for loop with the size of list variable. where the value of

int sz=arr.size(); //its is 1 because there is only 1 variable inside array list.

you need to use the below code to loop with the size of string array inside the list as below.

int sz=arr.get(0).length;

Upvotes: 2

Related Questions