1

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
1
  • The simple way to do this is to more the array elements after the insertion / deletion point when you do the insert / delete. Commented Nov 1, 2018 at 2:25

4 Answers 4

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

I've been thinking about some code that shifts the array for a while, imagining it as some crazy long nest of loops but dude you hit it. Also weird that we did discuss about conditional statements but not a thing abut that "?" ternary operator so I researched right after seeing this. Thanks a lot! Also, is it possible to only delete one element out of two with the same name, using the inputted string and not the index? I think it is possible but consists of some flippy codes too
@inNeedOfHelp, you're welcome! Don't be afraid of shifting the array. As a matter of fact, array shifting is exactly what happens in java.util.ArrayList on calling remove method, but the shifting itself is implemented using System.arraycopy(...) method.
0

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.");
}  

Comments

0

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!

Comments

0

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.

3 Comments

I did not know that you could tinker with null values before! Surely will take this one in mind.
@inNeedOfHelp You are NOT tinkering with null values. You are explicity checking the value is not null before tinkering.
Meant to say that i didnt know it was possible to even at least reference a "null" since it itself gave the error kinda gave the "stay away from me" factor for me lol but anyways

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.