I created a custom 'text menu' that should print each String passed to it.
This is the class:

package com.github.geodox.areacalculator.menu;

public class Menu
{
    private static int index = 0;
    private static String[] menuItems;

    public void addItem(String menuItem)
    {
        menuItems = new String[index+1];
        menuItems[index] = menuItem;
        index++;
    }

    public void printMenu()
    {
        for(String menuItem : menuItems)
        {
            System.out.println(menuItem);
        }
    }

}

This is what is passed.

    Menu menu = new Menu();
    menu.addItem("rectangle");
    menu.addItem("square");
    menu.addItem("circle");
    menu.addItem("triangle");
    menu.addItem("trapezoid");
    menu.addItem("parallelogram");
    menu.printMenu();

However, this is what is printed:

null
null
null
null
null
parallelogram

Any ideas on why this is happenning?

Recommended Answers

All 3 Replies

Logical error in your program is you are intialising the String array "menuItems" inside the method addItem. So everytime when you call this method, a Array is created. so Atlast when you add the last item, for example "parallelogram" only that will be present in the newly created array.

You Should intialise the array "menuItems" outside the Method.
For ex. replace private static String[] menuItems; to `private static String[] menuItems = new String[6];

and remove the intialisation statement from the method.

But if the number of String you are going to pass is decided in the run time, you should use arraylist instead of arrays.`

And also you are using static keyword in the variables. so it will not belong to any instance of your class. Those variable belongs to the class itslef.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.