alammd
alammd

Reputation: 339

Unable to change variable's value inside an Array

I am trying to see how I can change the DateToStr (Unix time) when an Array item is showing. Currently it is always showing the same time.

public class Testarray {
    public static void main(String args[]) {
        SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");
        String  DateToStr = format.format(new Date());

        String[] anArray = {
            "001,"+ DateToStr +",,F,", "001,"+ DateToStr +",,F,", "001,"+ DateToStr +",,F,"
        };

        for (int i =0 ;i <anArray.length;i++) {
             try{
                 //  show array element every 10sc with new date and time. 
                 Thread.sleep(10000);
             }catch(InterruptedException ex){

             }
             System.out.println(anArray[i]);
        }
    }

Current output:

001,181102074606,,F,
001,181102074606,,F,
001,181102074606,,F,

Expected output: each output should have new date as it is 10 seconds delayed.

Upvotes: 0

Views: 99

Answers (2)

Pooja Aggarwal
Pooja Aggarwal

Reputation: 1213

DateToStr variable is common for all the three entries in the array and that is why it is giving you same date every time. If you want your date to be new every time then you will have to get that value in the loop before sleep method.

Try this,

  SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");

        String[] anArray = new String[3];

        char c ='E';
        for (int i =0 ;i <anArray.length;i++) {

            try{
                anArray[i]= "001,"+ format.format(new Date()) +",,"+c+",";
                c++;
            //  show array element every 10sc with new date and time. 
                Thread.sleep(10000);
            }catch(InterruptedException ex){

            }

            System.out.println(anArray[i]);

        }

Upvotes: 3

Paweł Grzybek
Paweł Grzybek

Reputation: 57

You need to update your DateToStr value every time you insert. And you insert everything at once. You only read with 10s delay.

Correct is to wait 10s between inserts, and read date each time at insert time.

  SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");

    String[] anArray = new String[3];
    for(int i = 0; i < anArray.length; ++i) {
        try {
            // Sleep before inserting
            Thread.sleep(1000);
            // Insert with new value every time
            anArray[i] = "001,"+ format.format(new Date()) + ",,F,";
            System.out.println(anArray[i]);
        } catch (InterruptedException ex) {
        }
    }

Upvotes: 0

Related Questions