0

I'm trying to learn Java and I'm working on my project "Collection of programs" // very simple ones: like a basic calculator, factorials, reversing numbers etc. These programs are divided into categories like Mathematics, Drawings ... The problem is that maybe in the future I will want to have more categories/programs in it. I want to use arrays so I don't have to re-write my code every time I add a new program/category.


I have created an array of strings and updated my method welcomeUser. But I don't know how to deal with my chooseBlock method and switch. I would like to have as many cases as blocks in my Array.

Thank you very much for every help


public class Program {

    Scanner scan = new Scanner(System.in);

    private boolean programRunning = true;

    public void run() {
        System.out.println("Welcome in my program! (version 1.0.0)");
        while (programRunning) {
            welcomeUser();
            chooseBlock();
        }

    }

    public void welcomeUser() {
        System.out.println("You can choose from these blocks:\n"
                + "[1.Mathematic Block]\t"
                + "[2.Drawing block]\t"
                + "[3.Else...]\t"
                + "[4.Exit]\n"
                + "Select with a number and press ENTER");
    }

    public void chooseBlock() {
        int block = 0;
        block = scan.nextInt();
        switch (block) {
            case 1:
                System.out.println("You've choosen Mathematic Block");
                Mathematics maths= new Mathematics();
                maths.run();
                break;
            case 2:
                System.out.println("You've choosen Drawing block");
                Drawings drawings = new Drawings();
                drawings.run();
                break;
            case 3:
                System.out.println("You've choosen Else block");
                break;
            case 4:
                System.out.println("Exiting the program");
                programRunning = false;
                break;
            default:
                System.out.println("Invalid input. Try again.");
                break;
        }
        System.out.println("");
    }

}

private String[] blocks
        = {"Mathematic Block", "Drawing Block", "Else", "Exit"};

public void welcomeUser() {

   System.out.println("You can choose from these blocks:\n");
   for (int i = 0; i < blocks.length; i++) {
        System.out.print("[" + (i + 1) + ". " + blocks[i] + " ]\t");
        if ((i + 1) % 4 == 0) {
            System.out.println();
        }
   }
   System.out.println();
   System.out.println("Select with a number and press ENTER");
}
2
  • 1
    Your problem is a design problem. I.e. how to make this app easy to extend. That's a difficult problem, usually not for beginners. Moreover, there is more than one good answer for this kind of problems. I suggest to keep your code as simple as possible. This makes things easy later on. No need to use Arrays when you don't need them right now. When you want to add another category, then you can ask a question about that. Commented Apr 12, 2018 at 11:17
  • 1
    The short answer, you want to use something like the strategy pattern. Each category will have it own strategy implementation. When you need to add a new category, you implement a new strategy. Know, instead of a switch you just have to get the instance of Strategy that is store in an array, the index will match the array of category. Simple and evolutive. But the first implementation take time since you need to have a strategy well defined. Strategy or State pattern are two similar, I might mix those... Commented Apr 12, 2018 at 11:23

1 Answer 1

1

Basically you want easy extensibility of categories. There are many ways to achieve this. I'll sketch one approach for starters.

First of all I'd explicitly model categories in a class like Category:

public abstract class Category {
    public abstract String getTitle();
    public abstract void run();
}

Each of the specific categories will have its own class, extending Category

public class Mathematics extends Category {
    public String getTitle() { return "Mathematic Block";}
    public void run() { ... }
}

Then you'll have a list of availabe categories:

private List<Category> categories = Arrays.asList(new Mathematics(), ...);

Now you can display the list of available categories as follows:

public void welcomeUser() {
    System.out.println("You can choose from these blocks:");
    for (int index = 0; index < categories.size(); index++) { 
        Category category = categories.get(index);
        System.out.println("[" + (index+1) + "." + category.getTitle() + "]");
    }
    // ...
}

And instead of switch you can do:

int block = scan.nextInt();
int selectedCategoryIndex = block - 1;
if (selectedCategoryIndex >= 0 && selectedCategoryIndex < categories.size()) {
    Category selectedCategory = categories.get(selectedCategoryIndex);
    selectedCategory.run();
}

If there's a new category, just add it to categories.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you all. I'm going to try it.
@user9635657 If you feel that my answer helped you, you could accept my answer.

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.