0

For some reason I'm getting an error with the Random object I created and I can't see any reason why. Can someone please help? I'd be very appreciative!

public static void experiment(String method, String testType, int arraySize, int trials){
    int[] intArray = new int[arraySize];
    Random rand = new Random();
    Long startTime;
    Long endTime;
    Long duration;
    String durationStr;
    String arraySizeStr = String.valueOf(arraySize);
    for (int i =0; i<arraySize;i++){
        intArray[i] = i;
    }
    if (method=="exhaustive"){
        if (testType =="worst"){
            for (int j = 0; j<= trials; j++){
                startTime = System.currentTimeMillis();
                exhaustive(intArray, intArray[arraySize-1]*3);
                endTime = System.currentTimeMillis();
                duration = endTime - startTime;
                durationStr = duration.toString();
                System.out.println("Exhaustive, Worst, " + durationStr + ", Array Size: " + arraySizeStr);
            }
        }
        else{
            for (int j = 0; j<= trials; j++){
                startTime = System.currentTimeMillis();
                exhaustive(intArray, rand.nextInt((arraySize -1) * 2));
                endTime = System.currentTimeMillis();
                duration = endTime - startTime;
                durationStr = duration.toString();
                System.out.println("Exhaustive, Best, " + durationStr + ", Array Size: " + arraySizeStr);
            }
        }
    }
rioV8
  • 24,506
  • 3
  • 32
  • 49
jstark523
  • 1
  • 1
  • 1
    What error are you getting? Since you haven't created a [mre], I can't test it. – NomadMaker Feb 10 '21 at 03:19
  • 'Random rand = new Random(); rand.nextInt(10);' Utilizing these two lines gives me the same error. The error states, "Save and re-use this "Random". sonarlint (java:S2119) – jstark523 Feb 10 '21 at 03:28
  • Don't redefine rand. Don't create a new Random() a second time. – NomadMaker Feb 10 '21 at 03:30
  • I'm sorry, I don't quite know what you mean? I don't think I'm redefining random. – jstark523 Feb 10 '21 at 03:35
  • You can create a `Random` instance and assign to class level static reference. Or can use `ThreadLocalRandom.current().nextInt()`. Don't share the `ThreadLocalRandom.current()` instance across threads. Always use `ThreadLocalRandom.current().nextInt` – Thiyanesh Feb 10 '21 at 03:42

0 Answers0