Avoiding null in an array?

remove undefined from array javascript es6
array filter nulls
null array in javascript
remove undefined from array lodash
handle null array in javascript
typescript filter null from array
javascript filter null values from object
how to check null value in array in javascript

I'm a novice coder and we are given a task in college to only use Arrays (I asked the teacher and said no array lists or whatsoever, wants to do it the rough way)

its about making an array that you are able to insert, search, or delete a value in it. I figured out the most of it by searching and applying out solutions.

But they wanted an output so that if I delete THEN I search that value, it would display that the value is gone, but the problem is since that value is deleted Java places a null in there, so when the for loop cycles through all of the nulls it creates the dreaded NullPointerException error. I'm currently searching right now for solutions with these limitations but to no avail, plus my Java vocabulary and terminology is admittedly short at the moment :P

import static java.lang.System.out;
import java.util.Scanner;

public class JavaApplication 
{
    public static void main(String[] args) 
    {  
        Scanner kb = new Scanner(System.in);

        //initialize String array x20 
        String[] regName = new String[20];
        int regCount = 0;
        int func = 0;
        while (func == 0) //Main Menu Looper
        {    
            out.println("Select function by entering its number.");
            out.println("[1] Insert");
            out.println("[2] Search");
            out.println("[3] Delete");
            out.println("[4] Exit");
            out.print("Choose Operation: ");
            func = kb.nextInt(); //Choose Option
            out.print("======================================");
            out.print("\n");

            switch (func) 
            {    
                case 1: //Insertion
                         //set Array index start
                        char yesNo;
                    do 
                    {   
                        //Inserting into arrays loop
                        out.print("Insert student last name: ");
                        regName[regCount] = kb.next();
                        regCount++;
                        out.print("\n");

                        //Viewing loop
                        out.println("Student List: ");
                        for (int ctrl = 0; ctrl < regCount; ctrl++)
                        {
                        out.println(regName[ctrl]);
                        }
                        out.print("\n");

                        //Question loop
                        out.print("You want to insert again(Y/N):");
                        yesNo = kb.findWithinHorizon(".", 0).charAt(0);
                        if (yesNo == 'y' || yesNo == 'Y')
                        {
                            yesNo = 'y';
                        }   
                    } while (yesNo == 'y');
                func = 0;    
                break;   

                case 2: //Searching
                    out.print("Enter keyword: ");
                    String search = kb.next();
                    boolean found = false;
                    int searchCount = 0;
                    for (int ctrl = 0; ctrl < regCount; ctrl++) 
                    {
                        if (regName[ctrl].equalsIgnoreCase(search)) {
                        found = true;
                        out.println(search + " has " + " a match.");
                        }               
                        else
                        {
                        out.println(search + " has " + " not found.");
                        }    
                    }    
                    out.print("\n");
                    func = 0;
                break;  

                case 3: //Deleting
                    out.print("type surname you want to delete: ");
                    String toDelete = kb.next();
                    for (int ctrl = 0; ctrl < regCount; ctrl++) 
                    {
                        if (regName[ctrl].equalsIgnoreCase(toDelete)) {
                        regName[ctrl] = null;
                        out.println("Record deleted.");
                        }                
                    }    
                    out.print("\n");
                    func = 0;
                break;    

            } //switch
        } //while   
    } //main
} //class

Other answers propose checking for null. But this won't fix your problem. As the rest of your code expects no gaps in your list of students.

Try shifting the names after you delete some of them:

case 3: //Deleting
        out.print("type surname you want to delete: ");
        String toDelete = kb.next();
        int deleted = 0;
        for (int ctrl = 0; ctrl < regCount; ctrl++) {
            if (regName[ctrl].equalsIgnoreCase(toDelete)) {
                out.println("Record deleted.");
                deleted++;
            }
            if(deleted > 0) {
                int newCtrl = ctrl + deleted;
                regName[ctrl] = (newCtrl < regCount) ? regName[newCtrl] : null;
            }
        }
        regCount -= deleted;
        out.print("\n");
        func = 0;
    break;

This solution assumes that your application allows duplicated entries.

Also I've found that your search operation prints <Name> has not found multiple times even if there is a match. Try changing it like this:

case 2: //Searching
        out.print("Enter keyword: ");
        String search = kb.next();
        boolean found = false;
        int searchCount = 0;
        for (int ctrl = 0; ctrl < regCount; ctrl++) {
            if (regName[ctrl].equalsIgnoreCase(search)) {
                found = true;
                out.println(search + " has a match : #" + ctrl);
                break;
            }
        }
        if(!found) {
            out.println(search + " has not found.");
        }
        out.print("\n");
        func = 0;
    break; 

UPDATE: deleting only first occurrence

case 3: //Deleting
        out.print("type surname you want to delete: ");
        String toDelete = kb.next();
        int deletedIndex = -1;
        for (int ctrl = 0; ctrl < regCount; ctrl++) {
            if(deletedIndex >= 0) {
                int newCtrl = ctrl + 1;
                regName[ctrl] = (newCtrl < regCount) ? regName[newCtrl] : null;
            } else if (regName[ctrl].equalsIgnoreCase(toDelete)) {
                deletedIndex = ctrl;
                out.println("Record deleted : #" + deletedIndex);
                regCount--;
            }
        }
        out.print("\n");
        func = 0;
    break;

Program to remove empty array elements in PHP, How do you remove null values from an array in Java? A common way of avoiding the  NullPointerException  is to check for null : In the real world, programmers find it hard to identify which objects can be  null.   An aggressively safe strategy could be to check  null for every object. This, however, causes a lot of redundant null  checks and makes our code less readable.


When searching, check for null before calling equalsIgnoreCase on it.

if (regName[ctrl]!=null && regName[ctrl].equalsIgnoreCase(search)) {
    found = true;
    out.println(search + " has " + " a match.");
}               
else
{
    out.println(search + " has " + " not found.");
}  

How can I check whether an array is null / empty?, is commonly used to denote or verify the non-existence of something. Avoid null/undefined in JavaScript arrays How to avoid TypeError: Cannot read property ___ of undefined using Array.filter(Boolean) tl;dr : Array.filter(Boolean) filters out falsy values ( null , undefined , 0 , false , '' ) and avoids Cannot read property of undefined errors.


Consider Null checks whenever you code using any data structure for avoiding un-checked exceptions. So you can add the check first which executes first and if true then only proceeds further.

if (regname[ctrl] != null && regName[ctrl].equalsIgnoreCase(search)) {

Hope this helps you solve your problem!

How to Check Null in Java: 6 Steps (with Pictures), Avoid null/undefined in JavaScript arrays. How to avoid TypeError: Cannot read property ___ of undefined using Array.filter(Boolean). NullPointerException is thrown when program attempts to use an object reference that has the null value. Invoking a method from a null object. Accessing or modifying a null object’s field. Taking the length of null, as if it were an array. Accessing or modifying the slots of null object, as if it were an array.


Just do null checks: if (regName[ctrl].equalsIgnoreCase(search)) { can become if (regname[ctrl] != null && regName[ctrl].equalsIgnoreCase(search)) { and so on.

This is equivalent to:

if (regname[ctrl] != null)
{
    if (regName[ctrl].equalsIgnoreCase(search))
    {
        ...

Because of the way Java evaluates expressions the second part will only be done if the first is ok - in your case only try to use the array if the value at that index is not null)

If you want to impress your teacher break the insert search and delete into different methods.

Avoid null/undefined in JavaScript arrays · Code with Hugo, In your own functions, you can avoid creating null or undefined values to for avoiding null and undefined values, but remember, if the array  Avoid creating null and undefined values. In your own functions, you can avoid creating null or undefined values to begin with. There are a couple ways to do that built into JavaScript that spring


Handling null and undefined in JavaScript, Calling an instance method of a null object; Accessing or modifying a field of a null object; Taking the length of null as if it were an array  In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when program attempts to use an object reference that has the null value. These can be: Invoking a method from a null object. Accessing or modifying a null object’s field. Taking the length of null, as if it were an array.


Avoid Check for Null Statement in Java, error indicator, which is discouraged by Guideline 52, “Avoid in-band error indicators.” For methods that return a set of values using an array or collection, This noncompliant code example returns a null ArrayList when the  Null array. An array can be null. An array is by default initialized to null. This must be specified explicitly in local variables. The C# language also initializes array reference elements to null when created with the new keyword.


41. Return an empty array or collection instead of a null value for , Following program creates an array with null values. Convert it a list with not-null values only and then get the array of that list.Exampleimport  Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain null.