有一个函数 y=f(x),比如 y=2*x-1
如何在屏幕上输入,而被程序读取,实现对函数的计算?

解决方案 »

  1.   

    使用递归
    public int diGui(x){
        if (x == 0)
            return 1;
        return diGui(x) * 2 -1;
    }
      

  2.   

    比如我要在程序中计算一个函数表达式y=f(x),当x=0时的值,而这个函数表达式不是事先在程序中写好的,需要每次从屏幕输入,比如分别要计算:
    y=2*+1
    y=x*x+2*1+1
    等等...
    如何在屏幕上输入,而被程序读取,实现对函数的计算?
      

  3.   

    这个只要实现java运行中动态编译就ok,根据输入的函数表达式,把它转换为一个类的方法,然后把这个类编译,通过反射调用。主要用到javax.tools包给lz个例子import java.io.IOException; 
    import java.lang.reflect.Method; 
    import java.net.URI; 
    import java.util.Arrays;import javax.tools.JavaCompiler; 
    import javax.tools.JavaFileObject; 
    import javax.tools.SimpleJavaFileObject; 
    import javax.tools.StandardJavaFileManager; 
    import javax.tools.ToolProvider;public class CompileString { 
        public static void main(String[] args) throws Exception { 
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 
            System.out.println(""+ToolProvider.getSystemJavaCompiler()); 
            StandardJavaFileManager fileManager = compiler.getStandardFileManager( 
                    null, null, null);        StringObject so = new StringObject( 
                    "Function", 
                    "class Function {" 
                            + " public int multiply(int multiplicand, int multiplier) {" 
                            + " System.out.println(multiplicand);" 
                            + " System.out.println(multiplier);" 
                            + " return multiplicand * multiplier;" + " }" + "}");        JavaFileObject file = so;        Iterable files = Arrays.asList(file); 
            JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, 
                    null, null, null, files);        Boolean result = task.call(); 
            System.out.println(result); 
            if (result) { 
                Class clazz = Class.forName("Function");            Object instance = clazz.newInstance();            Method m = clazz.getMethod("multiply", new Class[] { int.class, 
                        int.class });            Object[] o = new Object[] { 3, 2 }; 
                System.out.println(m.invoke(instance, o)); 
            } 
        } 
    }class StringObject extends SimpleJavaFileObject { 
        private String contents = null;    public StringObject(String className, String contents) throws Exception { 
            super(URI.create("string:///" + className.replace('.', '/') 
                    + Kind.SOURCE.extension), Kind.SOURCE); 
            this.contents = contents; 
        }    public CharSequence getCharContent(boolean ignoreEncodingErrors) 
                throws IOException { 
            return contents; 
        } 
    }
      

  4.   

    看看这个帖子吧:http://topic.csdn.net/u/20110518/10/9e9d46a6-f6b9-4aac-8b62-0dcfe90ba1f2.html
      

  5.   

    int x = 0;
    Scanner sc = new Scanner(System.in);//用键盘从后台输入
    x = sc.nextInt();//将后台的输入赋给x。(注意:sc.nextInt()只接受整数)
    y = f(x);
    System.out.println(y);/*当程序运行到第二句时,你需要从后台也就是你说的屏幕输入数字,程序才会继续运行,否则程序会永远等待*/
      

  6.   

    这个 难度比较大哦、要时间、做了 一个 小时才这个样:
    你给100分,看有人做不、
    等高手用更简单的方法解决下子、主要是判断难啊、可以判断输入函数的正确性:
    import java.util.*;
    /**
     * 创建计算函数类,格式为 y = f(x)类型,
     * 第一个字符必须是y,第二个字符必须是=,其后的任意字符由 (0 - 9) 和 x ,
     * 以及 四则运算符构成 (+、-、*、/)
     * @author zhou
     *
     */
    public class CreateFunction {

    public static void main(String[] args){
    while(true){
    Scanner input = new Scanner(System.in);
    System.out.println("please input you funtion:");
    String functionStr = input.next();
    System.out.println(isValidFunction(functionStr));
    }
    }


    /**
     * 计算指定函数的y值
     * @param x值
     * @return y值
     */
    public static int functionCalculator(String function, int x){

    //不包含x,直接返回右边的值,有可能是表达式 
    if(function.indexOf("x") < 0 )
    {
    if(function.indexOf("*") < 0 &&
    function.indexOf("/") < 0&&
    function.indexOf("*") < 0 &&
    function.indexOf("/") < 0)
    {
    return Integer.valueOf(function.substring(2)).intValue();
    }
    else
    {
    return 0;
    }
    }
    return 0;
    }

    /**
     * 判断控制台输入的有效的函数
     * @return
     */
    public static boolean isValidFunction(String functionStr){

    //函数右边判断是否合法
     boolean rightValid = false;
    // System.out.println(functionStr);
     int index = 2;
     char rightChar = functionStr.charAt(index); 
     
     //System.out.println(rightChar);
     while(index < functionStr.length())
     {

     if(rightChar == 'x' || 
     Character.isDigit(rightChar) ||
     '+' == rightChar && index != 2||
     '-' == rightChar && index != 2   ||
     '*' == rightChar && index != 2    ||
     '/' == rightChar && index != 2 
     )
         {
     if(index > 2 && functionStr.charAt(index-2)=='x' && 
     ((Character.isDigit(rightChar)) ||
     (rightChar == 'x')))
     {
     rightValid = false;
     break;
     }
     if(functionStr.endsWith("*") || functionStr.endsWith("/")
       || functionStr.endsWith("+") || functionStr.endsWith("-"))
     {
     rightValid =false;
     break;
     }
     
          rightValid = true;
     rightChar = functionStr.charAt(index++);
          continue; 
         }
     else
     {
     rightValid = false;
       break;
     }
     }
     
     
     //函数左边是否合法
     boolean leftValid = false;
     if(functionStr.startsWith("y="))
     {
     
     leftValid = true;
     }  return leftValid && rightValid;
     
    }
    }
      

  7.   


    谢谢了!
    已经有很好的思路,等待高手完善。如果能解决诸如:log、sin、cos等输入就更完美了。):