[英]How can I prioritize math operations in my own calculator written with swing library or add paranthese button to prioritize calculate in java or
有誰知道我如何優先考慮 javax.swing 庫中的操作? 例如,如果我想求和,我在從 JFrame 創建 object 之后執行此操作:
//create a variable for save before click =
int total1 = 0;
//set the frame's size
setSize(600,600);
//create a text field for show numbers
JTextField t = new JTextField();
t.setBounds(100,100,100,100);
add(t);
//create a button for 1
JButton b1 = new JButton();
//edit button 1
b1.setText("1");
b1.setBounds(300,100,80,80);
//set a action for button 1
b1.addActionListener(new
ActionListener(){
public void actionPerformed(){
//write the number on text field.
t.setText(t.getText() +
b1.getText());
}
}
//The 2nd button.
JButton b2 = new JButton();
b2.setText("2");
b2.setBounds(400,100,80,80);
b2.addActionListener(new
ActionListener(){
public void actionPerformed(){
t.setText(t.getText() +
b2.getText());
}
}
//create a + button for sum.
JButton plus = new JButton();
plus.setText("+");
plus.setBounds(500,100,80,80);
plus.addActionListener(new
ActionListener(){
public void actionPerformed(){
//catch total1 from saved numbers and sum them and save.
total1 = total1 +
Integer.parseInt(t.getText());
t.setText("");
}
}
//create a equal button
JButton equal = new JButton();
equal.setText("1");
equal.setBounds(300,100,80,80);
equal.addActionListener(new
ActionListener(){
public void actionPerformed(){
//catch the last total1 and sum with last number and save it into a variable and convert it to string and show it.
total2 = total1 + Integer.parseInt(t.getText());
t.setText(Integer.toString(total2));
total1 = 0;
}
}
我也知道這很簡單,需要嘗試捕獲或 if elses 但我不知道如何優先考慮 +、×、÷ 和 - 等操作? 我怎樣才能添加父母優先級? 我的主要問題是:如何在不帶括號和帶括號的情況下確定操作的優先級? 如果我想在自己的計算器中執行此操作,答案將是 14,但正確答案是 18.5 2+3×5+3÷2 我想控制我的操作在正確的時間工作(數學優先法則)。
感謝您關注我的問題。
創建中綴計算器比創建前/后綴計算器要困難得多,因為前/后綴計算器沒有運算順序問題。
但是有一個簡單的方法可以做到這一點:使用 ScriptEngine 在 JavaScript 中運行您的數學( https://javapapers.com/core-java/run-javascript-from-java/#:~:text=Run%20Javascript%20from %20Java%201%20ScriptEngineManager.%20ScriptEngineManager%20does,give%20some%20more%20example%20on%20this%20%E2%80%A6.%20 )。 您可能需要先進行正則表達式檢查,以確保腳本編寫正確並且不會導致任何惡意副作用
import javax.script.*;
public class JavaJavaScript {
public static void main(String args[]) throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
engine.eval("var x = 10;");
engine.eval("var y = 20;");
engine.eval("var z = x + y;");
engine.eval("print (z);");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.