可以要求用户选择他们想要运行的类,然后运行该类吗?

huangapple go评论55阅读模式
英文:

Is it possible to ask the user to pick what class they'd like to run and then run that class?

问题

我对JAVA编程不太了解,想知道是否可能以及如何要求用户输入他们想要运行的类,然后调用/运行该类?

示例:
我创建了两个类来解决汉诺塔问题,根据用户提供的n个盘子。一个类通过递归解决问题,另一个类通过迭代解决问题。当我询问用户要使用多少个盘子时,是否有可能询问他们想要如何解决该程序,无论是通过递归还是迭代,并且然后调用他们选择的类?

英文:

I'm new to JAVA programming, and was wondering if it's possible/how to ask the user to input what class they'd like to run and then call/run that class?

Example:
I created two classes to solve the Towers of Hanoi given (supplied by user) n amount of disks. One class solves the puzzle recursively and the other class solves the puzzle iteratively. When I am asking the user for the number of disks they'd like to use, is it possible to ask them how they would like to solve the program whether it be recursively or iteratively and then call the class that they chose?

答案1

得分: 1

// 接口定义
interface HanoiSolver {
    void solve(int n);
}

// 迭代求解器
class IterativeHanoi implements HanoiSolver {
    public void solve(int n) { ... }
}

// 递归求解器
class RecursiveHanoi implements HanoiSolver {
    public void solve(int n) { ... }
}

// 主类
public class MainClass {
    public static void main(String[] args) {
       // 可以根据需要更改输入方式
       String userInput = args[0];
       Integer n = Integer.parseInt(args[1]);

       HanoiSolver solver;
       if (userInput.equals("recursive")) {
            solver = new RecursiveHanoi();
       } else {
            solver = new IterativeHanoi();
       }
       solver.solve(n);
    }
}
英文:

You can do this in a pretty straightforward manner using a common interface both solvers implement.

interface HanoiSolver {
    void solve(int n);
}
// iterative solver
class IterativeHanoi implements HanoiSolver {
    public void solve(int n) { ... }
}
// iterative solver
class RecursiveHanoi implements HanoiSolver {
    public void solve(int n) { ... }
}
public class MainClass {
    public static void main(String[] args) {
       // you can change this to read input however you like
       String userInput = args[0];
       Integer n = Integer.parseInt(args[1]);

       HanoiSolver solver;
       if (userInput.equals("recursive")) {
            solver = new RecursiveHanoi();
       } else {
            solver = new IterativeHanoi();
       }
       solver.solve(n);
    }
}



</details>



# 答案2
**得分**: 1

是的这是可能的

这个版本乍一看可能会更加复杂但它更清楚地将各个部分分开在实际应用中接口和类通常会分别放在不同的文件中另外静态的 `chooseSolver` 方法可能会被移动到一个名为类似 `SolverFactory` 的单独类中

```java
import java.util.Scanner;
import java.util.Set;

public class Main {

    interface Solver {
        void solveIt();
    }

    static class SuperSolver implements Solver {
        public void solveIt() {
            System.out.println("SuperSolver总是解决任何问题");
        }
    }

    static class FastSolver implements Solver {
        public void solveIt() {
            System.out.println("没有人能击败FastSolver");
        }
    }
    
    public static void main(String[] args) {
        String in = askUserForOption();
        Solver s = chooseSolver(in);
        s.solveIt();
    }

    private static String askUserForOption() {
        String in;
        Set<String> validOptions = Set.of("A", "B");        
        try (Scanner sc = new Scanner(System.in)) {

            do {
                System.out.print("输入A或B:");
                in = sc.nextLine();
            } while (!validOptions.contains(in));
        }
        return in;
    }

    private static Solver chooseSolver(String in) {
        switch (in) {
        case "A":
            return new SuperSolver();
        case "B":
            return new FastSolver();
        default:
            throw new IllegalArgumentException("出现严重错误 - 给出了无效的选项");
        }
    }
}
英文:

Yes, that is possible.

This version may look a bit more complicated on first glance, but it separates the parts more clearly. The interface and the classes would usually be in separate files in real applications. Also, the static chooseSolver - method would possible be moved to a separate class named something like SolverFactory.

import java.util.Scanner;
import java.util.Set;
public class Main {
interface Solver {
void solveIt();
}
static class SuperSolver implements Solver {
public void solveIt() {
System.out.println(&quot;SuperSolver always solves anything&quot;);
}
}
static class FastSolver implements Solver {
public void solveIt() {
System.out.println(&quot;Noone beats the FastSolver&quot;);
}
}
public static void main(String[] args) {
String in = askUserForOption();
Solver s = chooseSolver(in);
s.solveIt();
}
private static String askUserForOption() {
String in;
Set&lt;String&gt; validOptions = Set.of(&quot;A&quot;, &quot;B&quot;);		
try (Scanner sc = new Scanner(System.in)) {
do {
System.out.print(&quot;Enter A or B: &quot;);
in = sc.nextLine();
} while (!validOptions.contains(in));
}
return in;
}
private static Solver chooseSolver(String in) {
switch (in) {
case &quot;A&quot;:
return new SuperSolver();
case &quot;B&quot;:
return new FastSolver();
default:
throw new IllegalArgumentException(&quot;something went terribly wrong - an invalid option was given&quot;);
}
}
}

答案3

得分: 0

根据代码是在内部使用还是作为库包使用而定。
在内部,您可以使用接口,然后分离出具体的实现。

在库中,您可以再次让用户调用接口方法,根据条件编写该接口的实现。

或者,如果您希望用户在运行时确定要使用的算法,则可以使用反射来决定创建哪个类的对象。

英文:

Depends on where this code is used internally or as library package.
Internally you can use interface and then seperate out the concrete implementation.

In library , you can again let user call interface method , write implementation of that interface based on condition.

Or if you want the user to determine the algo to use during the runtime then use Reflection to decide which class's object to create.

huangapple
  • 本文由 发表于 2020年10月12日 22:00:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/64319379.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定