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");
}
Arrayswhen you don't need them right now. When you want to add another category, then you can ask a question about that.switchyou just have to get the instance ofStrategythat 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...