【问题标题】:How to ask user input to call a method [closed]如何要求用户输入调用方法[关闭]
【发布时间】:2014-08-23 21:03:48
【问题描述】:

我想做一个简单的计算器,一个可以计算平方米,一个可以计算“pi”或任何你能想象到的东西。但我想在运行程序的开头调用我想使用的计算器。所以如果我运行程序,系统会问我是否要使用计算平方米或 pi 的计算器。例如输出:

  1. 您要使用哪个计算器: SquareMeter
  2. 输入第一个数字: 2
  3. 输入第二个数字: 4
  4. 你的答案是: 8

我的问题是,我该怎么做?

【问题讨论】:

  • 您是否尝试过使用谷歌搜索“从 Java 中的控制台读取”?如果没有,那就去做吧。
  • 欢迎来到 SO。请阅读How to Ask。网上有很多java教程。

标签: java calculator


【解决方案1】:

我能想到两种方法,第一种方法相当复杂,但要处理各种各样的潜在用户输入,第二种方法很简单,使用基本的编程概念,但功能有限。

使用this question 中描述的任何方法。 (我是新人。如果引用其他类似的答案是违反规则的,请告诉我,请不要讨厌。)

示例代码:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class StackTester {
    public static void main(String[] args) {
        Method method = null;
        // set methodName equal to the name of the method to be called
        String methodName = "hi";
        StackTester cls = new StackTester();
        Class c = cls.getClass();
        try {
            method = c.getMethod(methodName, int.class);
            System.out.println("method = " + method.toString()); 
        } 
        catch (SecurityException e) {
            System.out.println("fail1");
        } 
        catch (NoSuchMethodException e) {
            System.out.println("fail2");
        }
        try {
              System.out.println(method.invoke(cls, 8)); 
            }
        catch (IllegalArgumentException e) {
            } 
        catch (IllegalAccessException e) {
            } 
        catch (InvocationTargetException e) {
    }
}
    public int hi(int x) {
        return x;
    }
}

另一种方法是使用大量 if/else 或 switch/case 与 Scanner 读取用户输入来调用您希望调用的所有方法名称。

只是一个供将来参考的建议:尝试自己进行一些研究!试图回答这个问题,我学到了很多东西。

【讨论】:

    【解决方案2】:

    您可以使用Scanner

    例如:

    Scanner in = new Scanner(System.in);
    
    System.out.println("which calculator you want to use?");
    
    String calculatorType = in.nextLine();
    
    System.out.println("enter first number: ");
    
    String firstNumber = in.nextLine();
    
    System.out.println("enter second number: ");
    
    String secondNumber = in.nextLine();
    
    if(calculatorType.equals("SquareMeter")
        //do something
        System.out.println("Your answer is: " + doSomeCalculation(firstNumber, secondNumber));
    

    在 if 语句中,您可以根据用户要求的计算调用不同的方法。在这种情况下,这将是 "SquareMeter",所以 doSomeCalculation() 看起来像这样:

    int doSomeCalculation(int a, int b){
        return a*b;
    }
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多