-1

I am trying to print an array of randomly generated sets of three numbers. Sometimes the sets include a null value when they are printed to the console. Curiously, it is only and always, two of the sixty-six randomly produce sets of three digits that contain a null value.

  1. If I check for null with an if statement using the == operator, then Java interprets it to mean "ignore the value" or "ignore the operation" since the code inside the wiggly brackets is not executed and the null values print to my console.

  2. If I check for null with an if statement using the .contains() method, I get a NullPointerException

  3. If I check for null with an if statement using the .equals() method, then the program may stop upon reaching this check. If I rebuild the program and re-run it, then Java interprets it to mean "ignore the value" or "ignore the operation" since the code inside the wiggly brackets is not executed and the null values print to my console.

  4. I cannot use Array[i].charAt(null) because the charAt() method takes an int.

  5. I cannot use numS[index].compareTo(null) because the .compareTo() method takes a String for an argument.

In an attempt to figure out the reason behind this, I used the Math.Random method or a Random rng = new Random(); Object. This did not change the outcome.

Any assistance will be greatly appreciated.

I checked the post [Check if array is NULL at a Specific Index returns NullPointerException], but it did resolve my issue.

I also modified my original code as below per the aforementioned post, to:

 while (randomNum.size() < 66) {
        for (int index = 0; index <= 2; index++) {
            int n = obj.rng.nextInt(4)+1;
            String s = Integer.toString(n);

            if (s == null)
                {n = obj.rng.nextInt(4)+1;
                s = Integer.toString(n);
                numS[index] = s;}

and also to:

int n = obj.rng.nextInt(4)+1;
            String s = Integer.toString(n);

            if (s.equals(null))
                {n = obj.rng.nextInt(4)+1;
                s = Integer.toString(n);
                numS[index] = s;}

But that did not resolve my issue either.

Here is my code:

import java.util.*;
import java.lang.*;
public class TestingTests{ 
public static void main(String[] args) { //main() method.
    obj.uniqueString();
} //end of main() method

void uniqueString() {
    while (randomNum.size() < 66) {
        for (int index = 0; index <= 2; index++) {
            int n = obj.rng.nextInt(4)+1;
            numS[index] = Integer.toString(n);

            if (numS[index] == null)
                {n = obj.rng.nextInt(4)+1;
                numS[index] = Integer.toString(n);}
            else if (randomNum.size() == 66)
                {ArrayList randomList = new ArrayList(randomNum);
                System.out.println("This is the size of randomList: " + randomList.size());
                Collections.sort(randomList);
                System.out.println("This is a randomList: " + randomList);
                break;
            }
            else randomNum.add(Arrays.toString(numS));
        }
    }
}

int temp = 0, count = 0;
static TestingTests obj = new TestingTests();
String[] numS = new String[3];
Random rng = new Random();
Set<String> randomNum = new HashSet<>();
ArrayList randomList = new ArrayList(randomNum);

}// end of MyClass

Here is an example of the output with the null values that I am trying to rid:

This is the size of randomList: 66
This is a randomList: [[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 1, 4], [1, 2, 1], [1, 2, 2], [1, 2, 3], [1, 2, 4], [1, 3, 1], [1, 3, 2], [1, 3, 3], [1, 3, 4], [1, 4, 1], [1, 4, 2], [1, 4, 3], [1, 4, 4], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 1, 4], [2, 2, 1], [2, 2, 2], [2, 2, 3], [2, 2, 4], [2, 3, 1], [2, 3, 2], [2, 3, 3], [2, 3, 4], [2, 4, 1], [2, 4, 2], [2, 4, 3], [2, 4, 4], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 1, 4], [3, 1, null], [3, 2, 1], [3, 2, 2], [3, 2, 3], [3, 2, 4], [3, 3, 1], [3, 3, 2], [3, 3, 3], [3, 3, 4], [3, 4, 1], [3, 4, 2], [3, 4, 3], [3, 4, 4], [3, null, null], [4, 1, 1], [4, 1, 2], [4, 1, 3], [4, 1, 4], [4, 2, 1], [4, 2, 2], [4, 2, 3], [4, 2, 4], [4, 3, 1], [4, 3, 2], [4, 3, 3], [4, 3, 4], [4, 4, 1], [4, 4, 2], [4, 4, 3], [4, 4, 4]]

Process finished with exit code 0
DwB
  • 37,124
  • 11
  • 56
  • 82
  • You need to use debugging statements in your code – g00se Jun 17 '23 at 21:20
  • (numS[index] == null) is always false, not sure how you are getting this error, [maybe Random isnt intanced correctly](https://stackoverflow.com/questions/15364237/random-generator-returns-null) – Daniel Hernández Jun 17 '23 at 21:27
  • 1
    It would also help to describe your [goal](https://technojeeves.com/index.php/aliasjava1/15-smart-questions) since you seem to be writing quite a lot of tortuous code for very little result. Realize too that you're using the *same array* all the time, constantly overwriting it, which is quite likely to be incorrect. – g00se Jun 17 '23 at 21:38
  • There is no way that `Integer.toString(n)` returns `null`, so there's to chance that `s == null` will ever be true. I suggest changing your array type from `String[]` to `int[]` to remove any possibility of nulls in arrays. Then render the arrays to strings at the latest point you can. – Bohemian Jun 17 '23 at 21:52
  • your nulls are basically the first 2 passes you do on the for since `numS` is instatiated with 3 empty spaces so at the start `numS = {null,null,null}` after your first passing of the for loop ( the index 0) you get your first number so it goes `numS = {1,null,null}` and this gets hadded to the `randomNum` set and then the 2nd pass ( the index 1) numS will be `numS = {1,2,null}` and randomNum will now have `randomNum = { [1,null,null],[1,2,null]}` this is why you only get 2 entries with nulls on the `randomNum` set – Anon Jun 18 '23 at 00:32
  • @DanielHernández, yes my `rng` is initialized outside of the `main` method. – Coding Noob Unfiltered Jun 18 '23 at 01:07
  • @Anon, I believe that you're correct. Wow, I can't believe that I didn't see this. I should move the `randomNum.add(Arrays.toString(numS));` outside of the `for` loop so that it doesn't add `numS[]` to `randumNum` until it has been iterated over three times and it doesn't contain any `null` spaces. I am embarrassed , thank you. – Coding Noob Unfiltered Jun 18 '23 at 01:14
  • @g00se I have a few months of coding, and I am not familiar with the debugging tools in an IDE yet. My goals are stated at the beginning of my post, "I am trying to print an array of randomly generated sets of three numbers. ". – Coding Noob Unfiltered Jun 18 '23 at 03:29
  • I've been programming Java more or less since it was invented and I can't remember having used a debugger more than twice and probably even then to debug into someone else's code. For quick and dirty, you can just put in a sysout but a better solution is to put in proper logging that can be turned off/up and down as you need it – g00se Jun 18 '23 at 16:17

3 Answers3

0
void uniqueString() {
    while (randomNum.size() < 64) {
        String[] numS = new String[3];
        for (int index = 0; index < numS.length; index++) {
            int n = obj.rng.nextInt(4) + 1;
            numS[index] = Integer.toString(n);
        }
        randomNum.add(Arrays.toString(numS));
    }
    ArrayList<String> randomList = new ArrayList<>(randomNum);
    System.out.println("This is the size of randomList: " + randomList.size());
    Collections.sort(randomList);
    System.out.println("This is a randomList: " + randomList);
}

Change it to a max of 64 (V3′​(4)=4^3), in your code it could return 66 because of the null values.

  • Daniel, thank you so much for your suggestions. But you solved my problem, without even referring to it, as use @Anon did above. The real issue is the I have `randomNum.add(Arrays.toString(numS));` included in my for loop, so the first iteration of `numS` is passed to `randomNum` with one instance of `int n = obj.rng.nextInt(4) + 1;` and two empty or `null` spaces. I appreciate your super concise code though. I need to refactor my code and make it as clean. – Coding Noob Unfiltered Jun 18 '23 at 01:21
0

As you know, null is a keyword specific to reference types and not for primitive types. So a small Java function to check if a string array is null at a particular index, could go something like this:

public class Main {
  public static void main(String[] args) {
    String[] arr = {"Stack", null, "Overflow"};
    System.out.println(isNull(arr, 1));
  }
  
  public static boolean isNull(String[] arr, int index) {
    arr[index] == null ? return true : return false;
    }
  }
}

And as you can see in this simplified (maybe super-simplified!) example, the output will be

true

So hope this answer helps! Thanks! Please correct me if I didn't exactly get you.

  • 1
    `if (expr) { return true; } else { return false; }` can/should be replaced by `return expr;` (seen this, written this very often lately¹) || `index` is undefined inside `isNull` || (¹ is this generated by AI?) – user16320675 Jun 17 '23 at 22:08
  • You can do the same thing doing `return (arr[index] == null)`, your method parameters are wrong, args in main and isNull are swapped. – Daniel Hernández Jun 17 '23 at 22:08
  • @DanielHernández, thanks for pointing it out, I have edited this. Yeah, i just might have over wrote the code. – Vaikan Peddi Jun 17 '23 at 22:12
  • You just change it for the ternary operator. Its the same as doing (like @user16320675 said) `if (expr) { return true; } else { return false; }` but in one line. – Daniel Hernández Jun 17 '23 at 22:30
  • @DanielHernández even simpler: `return arr[index] == null;` (brackets are not needed). Or even better, delete this method entirely and replace with `arr[i] == null` (preferred). – Bohemian Jun 17 '23 at 23:40
  • This is well-intentioned code, but it would add too many lines to my code. I appreciate all your suggestions though. – Coding Noob Unfiltered Jun 18 '23 at 00:58
  • @Bohemian, throw a _Scanner.close_ in there for good measure. Lol! – Reilas Jun 18 '23 at 01:01
0

"I am trying to print an Array of randomly generated sets of three numbers, and sometimes the sets include a null value ..."

There are a few inconsistencies with your code.

Consider the following.

iteration 1, index= 0, n= 2, numS= [2, null, null], randomNum= [[2, null, null]]
iteration 1, index= 1, n= 4, numS= [2, 4, null], randomNum= [[2, 4, null], [2, null, null]]
iteration 1, index= 2, n= 1, numS= [2, 4, 1], randomNum= [[2, 4, null], [2, 4, 1], [2, null, null]]
iteration 2, index= 0, n= 3, numS= [3, 4, 1], randomNum= [[2, 4, null], [2, 4, 1], [3, 4, 1], [2, null, null]]
iteration 2, index= 1, n= 3, numS= [3, 3, 1], randomNum= [[2, 4, null], [2, 4, 1], [3, 4, 1], [3, 3, 1], [2, null, null]]
iteration 2, index= 2, n= 1, numS= [3, 3, 1], randomNum= [[2, 4, null], [2, 4, 1], [3, 4, 1], [3, 3, 1], [2, null, null]]
iteration 3, index= 0, n= 3, numS= [3, 3, 1], randomNum= [[2, 4, null], [2, 4, 1], [3, 4, 1], [3, 3, 1], [2, null, null]]
iteration 3, index= 1, n= 4, numS= [3, 4, 1], randomNum= [[2, 4, null], [2, 4, 1], [3, 4, 1], [3, 3, 1], [2, null, null]]
iteration 3, index= 2, n= 2, numS= [3, 4, 2], randomNum= [[2, 4, null], [2, 4, 1], [3, 4, 1], [3, 3, 1], [3, 4, 2], [2, null, null]]
...

"I am trying to print an array of randomly generated sets of three numbers. ..."

You can use the following example.

List<Set<Integer>> list = new ArrayList<>();
Set<Integer> set;
Random random = new Random();
for (int count = 1; count <= 66; count++) {
    set = new HashSet<>();
    do {
        set.add(random.nextInt(1, 5));
    } while (set.size() != 3);
    list.add(set);
}
System.out.println(list);

Output

[[1, 2, 4], [1, 3, 4], [2, 3, 4], [1, 3, 4], [1, 3, 4], [1, 2, 3], [1, 3, 4], [1, 3, 4], [1, 3, 4], [1, 2, 4], [1, 2, 4], [2, 3, 4], [2, 3, 4], [2, 3, 4], [1, 2, 4], [2, 3, 4], [1, 2, 3], [2, 3, 4], [1, 2, 3], [1, 2, 4], [1, 2, 3], [2, 3, 4], [1, 2, 4], [1, 2, 4], [1, 2, 4], [1, 2, 3], [1, 3, 4], [1, 2, 4], [2, 3, 4], [1, 3, 4], [1, 3, 4], [1, 3, 4], [2, 3, 4], [1, 2, 3], [1, 2, 3], [2, 3, 4], [1, 2, 4], [1, 2, 3], [2, 3, 4], [1, 3, 4], [2, 3, 4], [2, 3, 4], [1, 2, 4], [2, 3, 4], [2, 3, 4], [1, 2, 4], [1, 2, 4], [1, 2, 4], [2, 3, 4], [1, 2, 4], [1, 2, 4], [2, 3, 4], [1, 2, 4], [1, 2, 4], [1, 3, 4], [1, 2, 3], [2, 3, 4], [2, 3, 4], [2, 3, 4], [1, 2, 3], [1, 3, 4], [1, 2, 4], [2, 3, 4], [2, 3, 4], [2, 3, 4], [2, 3, 4]]
Reilas
  • 3,297
  • 2
  • 4
  • 17
  • This is such beautiful and concise code. I realized the issue when I first read your graphic description of the inconsistencies on the iterations over `numS`, and then I read user @Anon's comment. Thank you so much. User @Daniel Hernández also shows it on his code, although he doesn't point it out. I am learning something new with your code; you are declaring a List of Sets here, `List> list = new ArrayList<>();`, and it never occurred to me to do that. Amazing. I'll refactor my code now. – Coding Noob Unfiltered Jun 18 '23 at 01:35
  • @Eleazar, thanks, glad it helped. My recommendation here, to avoid a similar mistake, would be to start your design using local variables, and only increase their scope as needed. – Reilas Jun 18 '23 at 02:04
  • Thanks again. I started using this coding philosophy yesterday after watching "How Nasa writes space-proof code" at https://www.youtube.com/watch?v=GWYhtksrmhE, so I am improving. In my refactored code, I moved all declarations and Initializations inside my `void uniqueString()` method. By the way, I couldn't use `random.nextInt(1, 5)`, so I used`rng.nextInt(4) + 1);` instead. – Coding Noob Unfiltered Jun 18 '23 at 03:02
  • This is actually quite different to your original output, and to that of @Daniel Hernández, in that it supplies groups of three with no repetition. Yours allowed, say `[ 3, 3, 4]` but it's not clear quite what your requirement is – g00se Jun 18 '23 at 16:22
  • @g00se, the reason I did that is because they had mentioned, _"... sets of three numbers ..."_. – Reilas Jun 18 '23 at 18:50
  • Oh yes. But of course, that phrase might have been used in the loose sense of just "three numbers chosen from 1, 2, 3, 4" – g00se Jun 18 '23 at 18:54
  • @g00se, I guess ask them specifically, they may not realize it's non-repeating. – Reilas Jun 18 '23 at 18:56