Generating Random Date - java

I'm a novice Java student. I have only been studying programming for a few months at school, and so I am currently pretty bad at it, and often feel stuck doing my assignments.
Anyway, I have a question regarding an assignment. I have been looking around and not quite finding the answers I need, so I was hoping to find some help on here. It would be much appreciated. My assignment goes like this: "Write a program that creates a Date object and a Random object. Use the Random object to set the elapsed time of the Date object in a loop to 10 long values between 0 and 100000000000 and display the random longs and the corresponding date and time."
We were just introduced to the classes java.util.Random and java.util.Date to work with this assignment, and are expected to use them to create the needed Date and Random objects.
The only things I really know how to do for this assignment are how to start the code:
public class RanDate {
public static void main(String[] args) {
And how to create the loop:
for (int i = 0; i <= 10; i++) {
I'm sorry if my question was too vague, or if I didn't ask something properly. This is my first time asking for help on this site. Thank you in advance for your help.

How about this?
Random rnd = new Random();
Date date = new Date(Math.abs(System.currentTimeMillis() - rnd.nextLong()));
System.out.println(date.toString());
Just subtract the actual time System.currentTimeMillis() and random generated long number with rnd.nextLong(). It's better finally wrap it all to Math.abs().

Try this code.
I think the assignment asks for the long to be the value in the date object, but I'm not shure.
public static void main(String[] args) {
Long max =0L;
Long min =100000000000L;
//Use the date format that best suites you
SimpleDateFormat spf = new SimpleDateFormat("dd/MM/yyyy");
for (int i = 0; i <= 10; i++) {
Random r = new Random();
Long randomLong=(r.nextLong() % (max - min)) + min;
Date dt =new Date(randomLong);
System.out.println("Generated Long:"+ randomLong);
System.out.println("Date generated from long: "+spf.format(dt));
}
}
Sample Output:
Generated Long:68625461379
Date generated from long: 05/03/1972

Related

Sum up all entries in an ArrayList<Integer> [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to add all elements in my ArrayList but it seems quite a challenge. Tried different methods and functions but none of them worked. Here is my code:
for (Kids ki : GroupOfKids) {
try {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String currentDate= dateFormat.format(date);
Date datum;
datum = dateFormat.parse(currentDate);
Date bornDate;
bornDate= ki.getbornDate();
int days = daysBetween(bornDate, datum);
//code above works fine..from here it's getting confusing
List<Integer> allKids;
allKids= new ArrayList<>();
allKids.add(days);
int total;
total = allKids.stream().mapToInt(Integer::intValue).sum();
System.out.print(total);
} catch (Exception e) {
e.printStackTrace();
}
}
I'm calculating how old are the "Kids" in days. I get an int and put the results in the ArrayList. I'm unable to get one result. I either get for each kid alone how old he/she is or I get both results if there are 2 for example stacked.
Example:
Kid 1 is 1234 days old
Kid 2 is 3422 days old
Result: 12343422
I expect 1234 + 3422 = 4656.
If there are more entries, then the sum of all together.
Can someone tell me where I'm making a mistake?
The first thing I see is using the old java.util.Date instead of the new java.time.LocalDate; then use the Period class to determine the number of days (probably could have modified your daysBetween if you had posted it). Like,
private static int getDaysOld(Date d) {
return Period.between(d.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(),
LocalDate.now()).getDays();
}
Then your stream should be used to map each Kids to their age and sum; like
int total = allKids.stream().mapToInt(k -> getDaysOld(k.getbornDate())).sum();
Let's say that you are doing sum in a wrong place.
You should define and initialize your list before the loop and do your summation after the loop ends.
List<Integer> allKids;
allKids = new ArrayList<>();
for( ... ) {
.
.
.
allKids.add(days);
.
.
.
}
int total;
total = allKids.stream().mapToInt(Integer::intValue).sum();
System.out.print(total);

Using Scanner to scan through a predefined list of strings in another class, and parse them to Ints in java

Quite a few labs have passed since my previous request for some advice and we are nearing midterms quite quickly! I am currently working on another lab right now and have ran into some slight difficulty that a little advice or guidance might help! Anyways here is whats going on!
I must have 3 classes in total:
(StationRecordMain, StationRecord, and TemperatureData)
He gave us the TemperatureData class pre-written and not able to modify it in anyway. This class holds a huge array of Strings all looking like this
"14762 20180829 89 70 80 9.6" . These are some junk number in the beginning we must throw away, the year month and day, the high temp, the low temp, avg, and difference.
This prewritten class also holds 2 methods in it, (hasNextTempRecord, getNextTempRecord).
My StationRecord class holds the following instance variables:
private int yearMonthDay = 0;
private int max = 0;
private int min = 0;
private int avg = 0;
private double dif = 0;
Finally, my MainStationRecord class holds the Scanner Object:
Scanner scan = new Scanner(tempdata.getNextTempRecord());
, an attempt to use the scanner to read through the predefined strings in the other class.
Anyways, I can supply more code that I have written but didnt want to flood this page with all of it, but those are the basics. I believe I am at a points where I know what I need to do, just need some guidance.
I need to use the Scanner to scan through all of those Strings on the other class (there are like 100 of them, so i'm assuming some sort of loop somewhere)
Then, I need to piece out each one of those strings and store their values in those private instance variables. Finally parsing them to ints and printing them out in the main class. That is where I am lost. Ive never used a scanner in such a way to do a preset of defined strings in a different class, moreover I have no experience on how to chop them up or parse them really.
Thus, if anyone could guide me in the right direction, It would be greatly appreciated! As I said before I can post the rest of my code I have written to make things easier if need be!
Until then thank you for looking!
I think if I understand it, You can easily do something like this: (I don't have complete code of yours, so this is just a suggestion)
class StationRecord {
private int yearMonthDay = 0;
private int max = 0;
private int min = 0;
private int avg = 0;
private double dif = 0;
public StationRecord(int yearMonthDay, int max, int min, int avg, double dif) {
this.yearMonthDay = yearMonthDay;
this.max = max;
this.min = min;
this.avg = avg;
this.dif = dif;
}
// rest of your code
}
public class Main
{
public static void main(String[] args) {
// rest of your codes
while (tempdata.hasNextTempRecord()) {
Scanner scan = new Scanner(tempdata.getNextTempRecord());
scan.next(); // read until a space and I don't save it for throw it away
new StationRecord(scan.nextInt(), scan.nextInt(), scan.nextInt(), scan.nextInt(), scan.nextDouble());
}
// rest of your codes
}
}
Thanks Andreas for comments too. This is what I understand and write it.

Iterator between two given hours

I was in a job interview and got this question: " Write a function that gets 2 strings s,t that represents 2 hours ( in format HH: MM: SS ). It's known that s is earlier than t.
The function needs to calculate how many hours between the two given hours contains at most 2 digits.
For example- s- 10:59:00, t- 11:00:59 -
Answer- 11:00:00, 11:00:01,11:00:10, 11:00:11.
I tried to do while loops and got really stuck. Unfortunately, I didn't pass the interview.
How can I go over all the hours (every second is a new time) between 2 given hours in java as explained above? Thanks a lot
Java 8 allows you to use LocalTime.
LocalTime time1 = LocalTime.parse(t1);
LocalTime time2 = LocalTime.parse(t2);
The logic would require you to count the amount of different digits in a LocalTime, something like
boolean isWinner(LocalTime current) {
String onlyDigits = DateTimeFormatter.ofPattern("HHmmss").format(current);
Set<Character> set = new HashSet<>();
for (int index = 0; index < onlyDigits.length(); index++) {
set.add(onlyDigits.charAt(index));
}
return set.size() <= 2;
}
You can loop between the times like this
int count = 0;
for (LocalTime current = time1; current.isBefore(time2); current = current.plusSeconds(1)) {
if (isWinner(current)) {
count++;
}
}
That's it.
The question is really more geared towards getting a feel of how you'd approach the problem, and if you know about LocalTime API etc.

Java: Create a Timer without a GUI [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
I'm working on a IRC Twitch.tv BOT (PircBot) and i want to implement a !uptime chatcommand which will display how long the Stream is online.
I searched in google a Bit and i only found solutions which requires a GUI.
Can Some1 tell me what libraries are good to use or give me some exampel code?
I need to display seconds, minutes, hours, days.
First i thought about doing a normal timer which counts +1 all seconds but i think its easier and there are some proper functions to handle such "count"-timers, right?
Im fine with any hints!
thanks :)
Thats what i came up with now:
In my Main class, i got a timer which i call with:
utimecounttimer();
My Timer looks like this:
public void utimecounttimer() {
uptimetimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (isstreamlive == true){
UptimeCount.Uptimestart();
}else{
UptimeCount.Uptimestop();
}
}
}, 1000, 1000);
}
and then my UptimeCount Class is here:
public class UptimeCount {
public static long startTime = 0;
public static long OnlineTimeMillis = 0;
public static float OnlineTimeSec = 0;
public static float OnlineTimeMin = 0;
public static float OnlineTimeHour = 0;
public static float OnlineTimeDay = 0;
public static void Uptimestart(){
if(startTime == 0){
startTime = System.currentTimeMillis();
}else
if(startTime != 0){
OnlineTimeMillis = System.currentTimeMillis()-startTime;
OnlineTimeSec = OnlineTimeMillis /1000F;
OnlineTimeMin = OnlineTimeMillis /(60*1000F);
OnlineTimeHour = OnlineTimeMillis /(60*60*1000F);
OnlineTimeDay = OnlineTimeMillis /(24*60*60*1000F);
}
System.out.println("Seconds"+OnlineTimeSec);
System.out.println("Minutes"+OnlineTimeMin);
System.out.println("Hours"+OnlineTimeHour);
System.out.println("Days"+OnlineTimeDay);
}
public static void Uptimestop(){
startTime = 0;
OnlineTimeMillis = 0;
OnlineTimeSec = 0;
OnlineTimeMin = 0;
OnlineTimeHour = 0;
OnlineTimeDay = 0;
}
}
And then, last but not least il get the Infos in chat with the following line in my Main class:
if (message.equalsIgnoreCase("!uptime")) {
sendMessage(channel," Stream is running for: "+UptimeCount.OnlineTimeDay +" Days, "+UptimeCount.OnlineTimeHour +" Hours. "+UptimeCount.OnlineTimeMin +" Minutes and " +UptimeCount.OnlineTimeSec +" Seconds.");
}
I didnt test it yet but i think i have to format the ms output of the floats and then it should be working, right?
You can use Joda Time to represent durations and times:
// at startup of the stream
DateTime startedAt = DateTime.now();
// later
Duration elapsed = new Duration(startedAt, DateTime.now());
And could use the solution described in this answer to format your output, to get a human readable output (ie. "1 hours 2 minutes").
Please also check Duration since it has methods like toStandardHours, toStandardMinutes which can be used to display the total number of hours/minutes/etc. elapsed (ie. "1 hours | 62 minutes").
// it will give you current time in mille seconds
long startTime = System.currentTimeMillis();
// Mill second diffrence
long OnlineTimeMillis = System.currentTimeMillis()-startTime;
// time diff in mille seconds since you are online
float OnlineTimeSec = OnlineTimeMillis /1000F;
// time diff in Minutes since you are online
float OnlineTimeMin = OnlineTimeMillis /(60*1000F);
// time diff in Hours since you are online
float OnlineTimeHour = OnlineTimeMillis /(60*60*1000F);
// time diff in days since you are online
float OnlineTimeDay = OnlineTimeMillis /(24*60*60*1000F);

Passing a string array in a main method

I have homework where I have to write a small program that asks for a number and returns the month assigned to that number.
So far I have written two different classes, one to prompt the user for int, and the other with the arrays of month. Now my problem is to pass over the months to the main class when the user enters a number.
So far for the main class I have this and I have no idea on how to proceed...
I get:
java:17: error: array required, but Date found System.out.println(monthName[index]);
I tried to be as detailed as possible.
import java.util.Scanner;
public class Driver {
public static void main(String[] args)
{
Utility input = new Utility();
final int MONTH_NAMES = 12;
int[] month = new int[MONTH_NAMES];
Date monthName = new Date();
{
System.out.println(input.queryForInt("Enter the number for a month ")) ;
}
for (int index = 0; index < 12; index++)
System.out.println(monthName[index]);
}
}
Your System.out line is not referencing the array you named month.
I don't think you intended to use Date monthName here
System.out.println(monthName[index]);
Judging by the number of indexes your for loop is counting, it looks like you wanted to use int[] month.
System.out.println(month[index]);
mouthName is a Date object, not an array. Also, why use a for loop to print out a whole year's mouth?
I think it can change the last for loop to System.out.printLn(mouthName.getMouth()) if the input.queryForIntmethod can successfully pass the int mouth to the mouthName object.

Categories

Resources