简体   繁体   中英

how to store strings from main class into an array and then print it - java

This is not the whole program which contains multiple classes, it is basically the algorithm. The problem I got is that I can't print out all the options, and what if I want to display the title first, then there would be a java.lang.ArrayIndexOutOfBoundsException: 0 error, how to count the number of options:

public static void main(String[] args)
{

        Menu menu=new Menu("Menu Title");

        menu.display();  

        menu.addOption("Do 1");
        menu.addOption("Do 2");
        menu.addOption("Do 3");
        menu.addOption("Do 4");

        menu.display();

        menu.addOption("Do 5");
        menu.addOption("Do 6");
        menu.addOption("Do 7");
        menu.addOption("Do 8");
        menu.addOption("Do 9");

        menu.display();       
}

public class Menu{
     int countOption;
     String options[];
     String menuTitle;

 public Menu(String menuTitle)
 {
    this.menuTitle = menuTitle;
 }       

 public void addOption(String addOption)      
 {   

    if (addOption != null)
    {
        countOption++;
        options=new String[countOption];
        options[countOption-1]=addOption;

    }   
 }

 public void display()   
 {
       System.out.println(menuTitle);
       int b;
       for (b = 0; b<countOption;b++)    
        System.out.println(options[b]);

  }

}

I agree with others here. I think it's best to modify the Menu Class so that it utilizes an ArrayList or List Interface (proffered) to hold Menu Options, that way it can easily grow dynamically as required and you have an abundance of elemental control options available to you.

I've taken your Menu Class and modified it so that menu options are stored within a List Interface of String ( List<String> ). I have also added two more constructors to the class, one of which is a empty constructor:

Menu menu = new Menu();

This allows for a menu to be declared but initialized later with whatever you like. And yet another constructor that allows for the Title so be supplied and either a String Array of menu options or comma delimited strings of Menu Options, for example:

String[] mOptions = {"Do 1", "Do 2", "Do 3"};
Menu menu = new Menu("My Title", mOptions);

                  OR

Menu menu = new Menu("My Title", "Do 1", "Do 2", "Do 3");

I've also added some methods to the Menu Class like addTitle() , overloaded the addOption() method to accept an String Array of menu options, changeOption() , insertOption() , removeOption() , getOptions() , and setOptions() .

The addTitle() method allows you to supply or change the Title of a specific Menu instance.

The addOption() method has been overloaded so that now a String Array of menu options can be added to the related Menu instance, for example:

String[] newMO = {"New Option 1", "New Option 2"}
Menu menu = new Menu("My New Menu");
menu.addOption(newMO);
menu.display();

The changeOption() method allows you to change (rename or make blank) an existing menu option by supplying the index value of where the option is located in the Menu and supplying the new option string that will replace the existing string, for example:

Menu menu = new Menu("\nMy NEW Menu Title :", "1) Do 1", "2) Do 2", "3) Do 3");
menu.display();

menu.changeOption(2, "3) What TO DO");
menu.display();

The console window will display:

My NEW Menu Title
1) Do 1
2) Do 2
3) Do 3

My NEW Menu Title
1) Do 1
2) Do 2
3) What TO DO

The insertOption() method allows you to insert a single menu option string at a specific index point within the related Menu instance, for example:

Menu newMenu = new Menu("\nMy NEW Menu Title :", "1) Do 1", "2) Do 2", "3) Do 3");
newMenu.display();
newMenu.insertOption(1, "2) What TO DO"); // Insert new option at index 1
newMenu.changeOption(2, "3) Do 2"); 
newMenu.changeOption(3, "4) Do 3");
newMenu.display();

And here is what this will display in console:

My NEW Menu Title:
1) Do 1
2) Do 2
3) Do 3

My NEW Menu Title:
1) Do 1
2) What TO DO
3) Do 2
4) Do 3

The removeOption() method allows you to remove a specific menu option from a specific Menu instance located at a specific index, for example:

newMenu.removeOption(1);

         OR

newMenu.removeOption("2) What TO DO");

The getOptions() method allows you to retrieve the current list of menu options for the current Menu instance, for example:

List<String> theMenuOptions = newMenu.getOptions();
System.out.println(String.join(", ", theMenuOptions)); 

The setOptions() method allows you to replace the menu options for the related Menu instance and set a new list of menu options by passing a String Array containing those new menu options, for example:

String[] newOptions = {"1) Play Sounds", "2) Continue Application", 
                       "3) Exit Application"};
newMenu.setOptions(newOptions); 
newMenu.display();

Here is the modified Menu class:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class Menu {
     List<String> options = new ArrayList<>();
     String menuTitle;
     String ls = System.lineSeparator();

    // Constructor 1 
    public Menu () {
        // Empty
    } 

    // Constructor 2
    public Menu (String menuTitle) {
        this.menuTitle = menuTitle;
    }

    // Constructor 3
    public Menu (String menuTitle, String... menuOptions) {
        this.menuTitle = menuTitle;
        this.options.addAll(Arrays.asList(menuOptions)); 
    }

    public void addTitle (String title) {
        this.menuTitle = title;
    }

    public void addOption(String menuOption) {   
        this.options.add(menuOption);
    }

    public void addOption(String[] menuOptions) {   
        this.options.addAll(Arrays.asList(menuOptions)); 
    }

    public void insertOption(int atIndex, String optionString) {   
        if (atIndex < 0 || atIndex > this.options.size()-1) {
            throw new IllegalArgumentException(
                    ls + ls+ "Menu.insertOption() Method Error!" + ls +
                    " The supplied Index (" + atIndex + ") is Out Of Bounds!");
        }
        this.options.add(atIndex, optionString);
    }

    public void changeOption(int atIndex, String newOption) {
        this.options.set(atIndex, newOption);
    }

    public void removeOption(int atIndex) {  
        if (atIndex < 0 || atIndex > options.size()-1) {
            throw new IllegalArgumentException(
                    ls + ls+ "Menu.removeOption() Method Error!" + ls +
                    " The supplied Index (" + atIndex + ") is Out Of Bounds!");
        }
        options.remove(atIndex);
    }

    public void removeOption(String optionString) {   
        options.remove(optionString);
    }

    public void display() {
        System.out.println(menuTitle);
        for (int b = 0; b < options.size(); b++) {   
            System.out.println(options.get(b));
        }
    }

    public List<String> getOptions() {
        return options;
    }

    public void setOptions(String[] menuOptions) {
        this.options.clear();
        this.options.addAll(Arrays.asList(menuOptions));
    }
}

And examples of how to use this particular class:

String ls = System.lineSeparator();

Menu[] menu = new Menu[4]; // Declare menu as a Menu Array

menu[0] = new Menu();
menu[0].addTitle("This is a Menu which only utilizes a Title." + ls +
        "This Menu instance used Constructor 1 of the " + ls +
        "Menu Class and contains no Menu Options. Of" + ls + 
        "course menu options can be added with the" + ls + 
        "addOption() method");
menu[0].display();  

menu[1] = new Menu(ls + "First TO DO Menu:" + ls +
            "This Menu instance used Constructor 2 of the " + ls +
            "Menu Class and contains 4 Menu Options which" + ls +
            "were added using the addOption() method.");
menu[1].addOption("A) Do 1");
menu[1].addOption("B) Do 2");
menu[1].addOption("C) Do 3");
menu[1].addOption("D) Do 4");
menu[1].display();

String[] mOptions = {"E) Do 5", "F) Do 6", "G) Do 7", "H) Do 8", "I) Do 9"};
menu[2] = new Menu(ls + "Second TO DO Menu:", mOptions);
menu[2].display();       
System.out.println("The above Menu instance used Constructor 3 of" + ls + 
        "the Menu Class and contains 5 Menu Options which" + ls +
        "were added using the mOptions String Array passed" + ls + 
        "to the contructor (see code).");

menu[3] = new Menu(ls + "Third TO DO Menu:", "J) Do 10", "K) Do 11", "L) Do 12");
menu[3].display();
System.out.println("The above Menu instance also used Constructor 3" + ls + 
        "of the Menu Class and contains 3 Menu Options which" + ls +
        "were supplied as comma delimited Strings to the" + ls + 
        "contructor.");

menu[1].addTitle(ls + "First TO DO Menu:" + ls +
                 "Removing 'A) Do 1' from the First menu with" + ls + 
                 "the removeOption() method.");
menu[1].removeOption("A) Do 1");
menu[1].display();
System.out.println("Notice now that 'A) Do 1' is not in the First Menu.");

menu[1].addTitle(ls + "First TO DO Menu - Dynamically Growing:" + ls +
                 "Re-inserting the 'A) Do 1' menu option with the" + ls + 
                 "insertOption() method and adding 3 additional menu " + ls + 
                 "options.");
menu[1].insertOption(0, "A) Do 1"); // Insert option at index 0
menu[1].addOption("Q) Do 5");
menu[1].addOption("R) Do 6");
menu[1].addOption("S) Do 7");
menu[1].display();
System.out.println("Notice now that 'A) Do 1' back in the First Menu" + ls + 
        "and 3 other menu options were dynamically added.");

System.out.println(ls + "Completely changing the First Menu to new menu" + ls +
                        "options using the setOptions() method.");
String[] newOptions = {"1) Play Sounds", "2) Continue Application", 
                       "3) Exit Application"};
menu[1].addTitle(ls + "New First Menu:");
menu[1].setOptions(newOptions);
menu[1].display();

System.out.println(ls + "Adding a new Menu.");
Menu newMenu = new Menu("\nMy NEW Menu Title :", "1) Do 1", "2) Do 2", "3) Do 3");
newMenu.display();

System.out.println(ls + "Inserting a new Menu Item and changing menu items after it.");
newMenu.insertOption(1, "2) What TO DO"); // Insert new option at index 1
newMenu.changeOption(2, "3) Do 2"); 
newMenu.changeOption(3, "4) Do 3");
newMenu.display();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM