-1

I am trying to create a program that generates random numbers. When the random number generated matches the current date it prints a counter for how many attempts it took. The date format is ddMMyyyy and the random numbers generated are 8 digits. At the end it prints the date and the count five times. This is what I have so far but it never returns an output.

import java.util.Random;
import java.util.Date;
import java.text.*;

public class Program1 {

    public static void main(String[] args) {

        Date date = new Date();
        Random value = new Random();
        int x = value.nextInt();

        int counter = 0;

        do {
            counter++;
        } while(!date.equals(value));

        if (date.equals(value)){
            for(int i = 1; i < 6; i++) {
                SimpleDateFormat sdf = new SimpleDateFormat ("ddMMyyyy");
                System.out.println("The date is " + sdf.format(date) + "!");
                System.out.println("The Count is: " + counter);
                System.out.println();
            }
        }
    }
}
Brad Larson
  • 170,088
  • 45
  • 397
  • 571
  • 3
    `Random value = new value();` That is not valid Java. When posting your code, please, use copy/paste from your IDE, do not retype the code. Also please take the [tour], visit the [help] and read [Ask] to learn how to use this site effectively. – Jim Garrison Mar 21 '21 at 21:10
  • The problem is that your `do...while` loop does not modify the value of `value`. It is set before the loop and does not change inside the loop. The only thing the loop does is increase the counter. – printf Mar 21 '21 at 21:35
  • 2
    By the way, the terrible `Date` & `SimpleDateFormat` classes were supplanted years ago by the modern *java.time* classes defined in JSR 310. – Basil Bourque Mar 21 '21 at 23:23
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Mar 22 '21 at 04:47
  • billy parker, please don’t create more work for others by vandalizing your own question so the answers no longer make sense. If you want to ask a new question, please ask a new question instead. – Ole V.V. Mar 23 '21 at 04:29

2 Answers2

3

Get a long number within the range 0 to the number of milliseconds from the epoch and apply the formatter to get the date string in the desired format. Then compare it with the date string of today.

Demo:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

class Main {
    public static void main(String[] args) {
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
        String strToday = sdf.format(now);
        int counter = 0;

        while (true) {
            // Instantiate Date with minutes of 8 digits
            Date date = new Date(TimeUnit.MILLISECONDS
                    .convert(ThreadLocalRandom.current().nextLong(10000000, 100000000), TimeUnit.MINUTES));
            String strDate = sdf.format(date);
            if (Objects.equals(strToday, strDate)) {
                for (int i = 1; i < 6; i++) {
                    System.out.println("The date is " + strDate + "!");
                    System.out.println("The Count is: " + counter);
                    System.out.println();
                }
                break;
            } else {
                counter++;
            }
        }
    }
}

A sample run:

The date is 21032021!
The Count is: 33263

The date is 21032021!
The Count is: 33263

The date is 21032021!
The Count is: 33263

The date is 21032021!
The Count is: 33263

The date is 21032021!
The Count is: 33263

Note that the java.util date-time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.*

Using the modern date-time API:

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

class Main {
    public static void main(String[] args) {
        // Change the ZoneId as applicable e.g. ZoneId.of("Europe/London")
        ZoneId zoneId = ZoneId.systemDefault();

        ZonedDateTime now = ZonedDateTime.now(zoneId);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("ddMMuuuu", Locale.ENGLISH);
        String strToday = dtf.format(now);
        int counter = 0;

        while (true) {
            // Instantiate Date with minutes of 8 digits
            LocalDate date = Instant
                    .ofEpochMilli(TimeUnit.MILLISECONDS
                            .convert(ThreadLocalRandom.current().nextLong(10000000, 100000000), TimeUnit.MINUTES))
                    .atZone(zoneId).toLocalDate();
            String strDate = dtf.format(date);
            if (Objects.equals(strToday, strDate)) {
                for (int i = 1; i < 6; i++) {
                    System.out.println("The date is " + strDate + "!");
                    System.out.println("The Count is: " + counter);
                    System.out.println();
                }
                break;
            } else {
                counter++;
            }
        }
    }
}

A sample run:

The date is 21032021!
The Count is: 9097

The date is 21032021!
The Count is: 9097

The date is 21032021!
The Count is: 9097

The date is 21032021!
The Count is: 9097

The date is 21032021!
The Count is: 9097

* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • @billyparker - *Why did you add milliseconds into the program?* - The `java.util.Date` represents the number of milliseconds since the standard base time known as "the epoch", namely `January 1, 1970, 00:00:00 GMT` (or UTC). The `.nextLong(10000000, millis)` part generates `long` value. between `10000000` and `millis`. – Arvind Kumar Avinash Mar 21 '21 at 22:29
  • @billyparker - *Is there a way to do this without using the time value and only the date value* - This solution is based on date only but in order to derive the date from milliseconds, you need to first get the date-time object from which you can extract the date. – Arvind Kumar Avinash Mar 21 '21 at 22:37
  • @billyparker - *Also does this generate numbers that are 8 digits long?* - Yes, I had missed this part. I've just updated my answer to meet this requirement. – Arvind Kumar Avinash Mar 21 '21 at 23:14
  • If running during the first 9 days of the month no true 8 digit number will be equal to the date. – Ole V.V. Mar 22 '21 at 05:06
0

Apart from using the long outdated and notoriously troublesome classes Date and SimpleDateFormat there are some errors in your program.

  1. As printf pointed out in a comment, inside your do-while loop you are neither modifying date nor value. So if they aren’t already equal before the loop, they will never be, and your loop will run indefinitely.
  2. date and value can never be equal. date is a java.util.Date, and value is a Random. A Date cannot be equal to a Random. It’s a confusing trait of Java that it’s syntactically allowed to compare them. A good IDE or a code analysis tool like SpotBugs should warn you that it’s unlikely to do what you wanted.
  3. int overflow: value.nextInt() can generate more than 4 billion possible values, from Integer.MIN_VALUE through Integer.MAX_VALUE. So it will take a while before your random number generator hits the right value. So your count will sometimes overflow the value that an int can hold, up to Integer.MAX_VALUE or a little over 2 billion.
  4. If your loop ends (after you have corrected the errors 1. and 2.), we already know that the loop condition is false. So you don’t need to test it once more with the if statement. Meaning: the if statement is superfluous. You may argue that it also does no harm, but it does: it confuses the reader.

The solution to avoiding Date and SimpleDateFormat is in the last half of the answer by Arvind Kumar Avinash. The solutions to 1., 2. and 4. are in the code in the other answers too. A solution to 3. would be using a long for the counter.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161