Kelley Sentelle
Kelley Sentelle

Reputation: 13

string input used in code?

So what I want to do is have a class that lets me choose another class to run. I currently have this set up by the user typing in a string that matches a string in a predetermined array. The part with an error is item runThis = new item(); which I fully expected to fail, but is there a way to do that which I am failing?

class Class1 {
    public static void main(String[] args){
        String[] options = new String[] {"Class2", "Class3", "Class4", "STOP"};
        String response = "";
        Scanner input = new Scanner(System.in);

        while (!response.equals("STOP")){
            System.out.println("Which program would you like to run?\nYour options are:");

            for (String item : options) {
                System.out.println(item);
            }

            response=input.nextLine();
            for (String item : options) {
                if(resonse.equals(item))
                item runThis = new item();
            }
        }
    }
}

Upvotes: 1

Views: 57

Answers (2)

Jaskaranbir Singh
Jaskaranbir Singh

Reputation: 2034

To execute classes dynamically from string variables, you can use:

Class c = Class.forName("className");
c.newInstance();

In your case, it would be:

for (String item : options){
    if(response.equals(item)){
        Class c;
        try {
            c = Class.forName(response);
            c.newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

Upvotes: 1

Andreas
Andreas

Reputation: 159086

Here is a way to do it fully type-safe, assuming your classes are Runnable:

    final List<Class<? extends Runnable>> programs = Arrays.asList(
            Class2.class, Class3.class, Class4.class);

    Scanner input = new Scanner(System.in);
    for (;;) {
        System.out.println("Which program would you like to run?\n" +
                           "Your options are:");
        for (Class<? extends Runnable> program : programs)
            System.out.println("  " + program.getSimpleName());
        System.out.println("  STOP");
        String response = input.nextLine();
        if (response.equals("STOP"))
            break;
        Class<? extends Runnable> programToRun = null;
        for (Class<? extends Runnable> program : programs)
            if (response.equals(program.getSimpleName())) {
                programToRun = program;
                break;
            }
        if (programToRun == null)
            System.out.println("Invalid program. Try again.");
        else
            try {
                programToRun.newInstance().run();
            } catch (Throwable e) {
                e.printStackTrace(System.out);
            }
    }

Upvotes: 1

Related Questions