Program that solves a simple math equation [closed]

寵の児 提交于 2019-12-14 03:32:51

问题


I'm having trouble understanding the syntax of Java and how to use Java to solve math equations. Below is just an example of a simple equation. I want the program to simply be able to output the result of the calculation. If anyone can help I would greatly appreciate it!

2.6^22 + 3.9^15

回答1:


See also the ScriptEngine.

import java.awt.*;
import java.awt.event.*;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.*;

class EvaluateString {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                JPanel gui = new JPanel(new BorderLayout(5,5));
                final JTextField input = new JTextField(
                        "Math.pow(2.6,22)+ Math.pow(3.9,15)",19);
                final JTextField output = new JTextField(15);
                output.setEditable(false);

                gui.add(input, BorderLayout.CENTER);
                gui.add(output, BorderLayout.PAGE_END);

                // obtain a reference to the JS engine
                final ScriptEngine engine = new 
                        ScriptEngineManager().getEngineByExtension("js");
                ActionListener calculate = new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        try {
                            String s = ((Double)engine.eval(input.getText())).toString();
                            output.setText(s);
                        } catch (ScriptException ex) {
                            ex.printStackTrace();
                        }
                    }
                };
                input.addActionListener(calculate);

                JOptionPane.showMessageDialog(null, gui);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
        SwingUtilities.invokeLater(r);
    }
}



回答2:


Try with

        Double sum=Math.pow(2.6, 22) + Math.pow(3.9,15);
        System.out.println("sum-->"+sum);



回答3:


How about this:

public class Equ {
   public static void main(String[] args)
   {
      System.out.println(Math.pow(2.6, 22) + Math.pow(3.9,15));
   }
}



回答4:


you could use the Math class, here,. in your case you can do:

Double result = Math.pow(2.6,22) + Math.pow(3.9, 15);

that's it,.




回答5:


Use the Math library.

 Math.pow(2.6,22) + Math.pow(3.9,15);

This will return a double

The first argument of pow function is the base and the second argument is the power.



来源:https://stackoverflow.com/questions/17182192/program-that-solves-a-simple-math-equation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!