I want an output of something like this
hi 2022.11.06 12:08:50 pm
hello 2022.11.06 12:09:40 pm
but I keep getting
hi 2022.11.06 12:08:50 pm
hello 2022.11.06 12:08:50 pm
even though I do the next input after a time interval.
Scanner reader = new Scanner(System.in);
Date dNow = new Date();
SimpleDateFormat dtformat = new SimpleDateFormat ("yyyy.MM.dd hh:mm:ss a");
for (int x = 0; x <= 5; x++){
String obj = reader.nextLine();
System.out.println(obj + dtformat.format(dNow));
}
I want an output of something like this
hi 2022.11.06 12:08:50 pm
hello 2022.11.06 12:09:40 pm
Java is, like most programming languages, imperative.
does not mean that 'y' is an alias for 'x'. It simply means: Resolve the expression
x, and take whatever that currently resolves to, then update the value ofyto be that value. Resolving expressionxsimply means: What is the current value of this variable.in other words:
This prints 5. It does not print 4.
In your code, you resolve the expression
new Date()exactly once, at the very start, and never again.dNowis set in stone once you ran it, and doesn't update. Simply rerundNow = new Date();to update.NB: This is obsolete, broken API; you should be using the
java.timepackage types, such asLocalDateTime, and thejava.timeformatters (DateTimeFormatter). The old stuff conflates human reckoning with computer reckoning, and thus fails when timezone definitions change. Which they do, every day.