解决简单数学方程式的程序 [英] Program that solves a simple math equation
本文介绍了解决简单数学方程式的程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法理解Java的语法以及如何使用Java来解决数学方程式.下面只是一个简单方程式的示例.我希望程序能够简单地输出计算结果.如果有人可以提供帮助,我将不胜感激!
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
推荐答案
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);
}
}
这篇关于解决简单数学方程式的程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文