Home > Enterprise >  Removing an array element after element has been used
Removing an array element after element has been used

Time:11-20

New to java here! I'm writing a Pizza program and am stuck on how to stop printing already selected items to the menu after each loop iteration. Can someone take a look at my code and help me out? We haven't covered user defined methods yet, which seems like it could simplify this whole project. Any tips on how to improve program functionality and readability would be appreciated, but my main concern is modifying the menu to only show items that have not been chosen, that way I can just update the quantity using the items index location and not have to define 100 variables.

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

        System.out.println("---------------------");
        System.out.println("Create Your Own Pizza");
        System.out.println("---------------------");
        
        
        //\\//\\//\\//\\//\\//\\PRINT TOPPINGS//\\//\\//\\//\\//\\//\\
        char userChar = 'y';
        String[] toppings = {"diced onion", "green pepper", "pepperoni", "sliced mushrooms", "jalapenos", "pineapple", "dry red pepper", "basil"};
        String[] choices = { "A. ", "B. ", "C. ", "D. ", "E. ", "F. ", "G. ", "H. "};
        //Enter topping menus loop
        while (userChar == 'y') {
            System.out.println("\nChoose your favorite toppings");

            for (int i=0; i<choices.length;   i) { 
                System.out.println(choices[i]   toppings[i]);   
            }

            
        //\\//\\//\\//\\//\\//\\CHOOSE TOPPINGS//\\//\\//\\//\\//\\//\\
        
          System.out.println("\nEnter a choice: ");
            String userToppings = sc.nextLine();
            //Need help removing each topping array element and choice array element after user adds to pizze
            if (userToppings.equalsIgnoreCase("A")) {
                System.out.println("Please choose one amount: ");
                System.out.println("a. 1/8 cup                 b. 1/4 cup");
                userToppings = sc.nextLine();
                if (userToppings.equalsIgnoreCase("A")) {
                    choices[0]="1/8 cup";
                }
                else {
                    choices[0]="1/4 cup";
                }
                System.out.println("Would you like to add more toppings? Type Y for yes or any other key to submit your recipe.");
                userChar = sc.next().charAt(0);
            }
            
            else if (userToppings.equalsIgnoreCase("B")) {
                System.out.println("Please choose one amount: ");
                System.out.println("a. 1/8 cup                 b. 1/4 cup");
                userToppings = sc.nextLine();
                if (userToppings.equalsIgnoreCase("A")) {
                    choices[1]="1/8 cup";
                }
                else {
                    choices[1]="1/4 cup";
                }
                System.out.println("Would you like to add more toppings? Type Y for yes or any other key to submit your recipe.");
                userChar = sc.next().charAt(0);
            }
           
 
            else {
                System.out.println("You did not enter a valid topping choice");
            }
    
        }

        //\\//\\//\\//\\//\\//\\PRINT RECIPE//\\//\\//\\//\\//\\//\\
        System.out.println("Your pizza recipe is: ");
        System.out.println(crustType   "\t1 ");
        System.out.println(sauceType   "\t"   sauceAmount);
        System.out.println(cheese   "\t\t"   cheeseAmount);
          
        //still developing this part just needed it to print the recipe 
        for (int i=0; i<toppings.length; i  ) {
            System.out.println(toppings[i]   "\t\t"   choices[i]);   
        }
    
            
    }
}

CodePudding user response:

Well, first off interesting comment styles :)

Your question is on how to remove an element from an array.

Anyways, it seems you are using Primitive Arrays which are in the form of type[] you can't really change the size of the array dynamically without implementing the entire functionality yourself.

There are a few ways to get around this limitation.

The first: Using a Dynamic Array (java.util.ArrayList)

You can use an ArrayList to create a dynamic array that allows for custom resizing on the fly without having to implement these functionalities. You can take a look at the docs here: https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

The defaults to working with an ArrayList goes like so:

import java.util.ArrayList;

ArrayList<String> myArray = new ArrayList<>();
myArray.add("hello"); // add an element to the end
myArray.get(0); // get the element at index 0; returns String
myArray.remove(0); // remove an element at an index
myArray.set(0, "foo"); // set the element at index 0 to foo

The second: Implementing the functionalities yourself You can create a function in your class that is called to update the values of the array when you want to delete a value from the array.

The first type is removal by equality (not a real name). This is when you want to remove elements that are similar to the one you want to remove and not by an index.

This can be done like with a function:

public static String[] removeElement(String[] array, String element)
{
   String[] temp = new String[array.length - 1];
   for(int i = 0, j = 0; i < array.length && j < temp.length; i  ) {
      if(!array[i].equals(element)) {
         temp[j] = array[i];
         j  ;
      }
   }
   return temp;
}

You can then use this function whenever you want to remove an element:

String[] temp = removeElement(new String[] { "hello", "world", ":)" }, "world");

Furthermore, you can remove by pure index, which can be done via:

public static String[] removeElement(String[] array, int index) 
{
   String[] temp = new String[array.length - 1];
   for(int i = 0, j = 0; i < array.length && j < temp.length; i  ) {
       if(i != index) 
         temp[j  ] = array[i];
   return temp;
}

You can call this with the following fashion:

String[] arr = removeElement(new String[] { "hello", "world", ":)" }, 0);

The third: Hiding the variables

There are multiple ways to do this, but all of them involve using a marker. A marker, in this case, is something that tells your program conditionals to not print something or vice versa.

The first approach is to mark a desired element as null, which you can do so by doing:

myArray[0] = null;

And when you are printing the array:

for(int i = 0; i < myArray.length; i  ) {
   if(myArray[i] != null) 
      System.out.println(myArray[i]);
}

However, this approach once you hide that element, your program can't go back, which isn't good if you just want to hide that element.

To truly hide a variable, you could declare another variable that stores the indices of the target array of elements you want to hide. For example:

int size = 5;
int[] elementsToHide = new int[size];
int[] elements = new int[size];
// ... add 5 elements to array:elements

// print 
for(int i = 0; i < size; i  ) {
   boolean isRemoveable = false;
   for(int j = 0; j < size; j  ) {
      if(i == j) {
        isRemoveable = true;
      }
   }
   if(!isRemoveable) {
     System.out.println(elements[i]);
   }
}

This approach truly hides an element from being seen to the user, but the program still knows that the element is still there.

CodePudding user response:

My understanding is that you want to remove items from the menu after they have been selected. I am assuming you must use arrays since this looks like a school assignment. If you are not limited to array then research HashMaps and ArrayLists.

I recommend the following:

  1. Put the code that displays the menu into a method.
  2. Create a third array that tracks if the user has selected a menu item.
  3. Update the array that tracks whether a menu item has been selected or not after the user selects a topping.
  4. Call the displayMenu() method after the user selects a menu choice to refresh the displayed menu.

See below for an example.

public static void main(String args[]) {
    displayMenu();
}
static void displayMenu() {
    String[] toppings = {"diced onion", "green pepper", "pepperoni", "sliced mushrooms", "jalapenos", "pineapple", "dry red pepper", "basil"};
    String[] choices = { "A. ", "B. ", "C. ", "D. ", "E. ", "F. ", "G. ", "H. "};
    boolean[] toppingSelected = { false, false, false, false, false, false, false, true};
    //Enter topping menus loop
    System.out.println("\nChoose your favorite toppings");

        for (int i=0; i<choices.length;   i) {
            if(toppingSelected[i] == false) {
             System.out.println(choices[i]   toppings[i]);      
            }
        }
    //System.out.println("test");
}

}

  •  Tags:  
  • java
  • Related