-6

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
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user2499376
  • 59
  • 1
  • 3

5 Answers5

4

See also the ScriptEngine.

enter image description here

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);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
2

Try with

        Double sum=Math.pow(2.6, 22) + Math.pow(3.9,15);
        System.out.println("sum-->"+sum);
bNd
  • 7,512
  • 7
  • 39
  • 72
2

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));
   }
}
jh314
  • 27,144
  • 16
  • 62
  • 82
1

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,.

simaremare
  • 401
  • 2
  • 10
1

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.

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56