Kalkulator yang diimplementasikan di Java, prinsipnya dibaca sebagai komentar kode, konten spesifik adalah sebagai berikut
kelas publik mycalculator {public static void main (string [] args) {string obj = "6+ (8/2)+6/3+1*8+30"; ArrayList <String> arrayList = strformat (obj); System.out.println (OBJ + "=" + CHOTULASI (arrayList)); } /** * Use subsequent expressions to calculate the result* 1. When the current string is a number, directly enter the stack* 2. When the current string is a calculator, take out the first two calculations on the stack* 3. Put the calculation result into the stack, and the last remaining element in the stack is the required result*/ private static int calculate(ArrayList<String> obj) { ArrayList<String> result = mengubah (obj); System.out.println (hasil); Stack <Integer> stack = stack baru <> (); untuk (int i = 0; i <result.size (); i ++) {string simbol = result.get (i); if (isDigital (simbol)) {// nomornya langsung stack.push (integer.parseint (simbol)); } else {// operator int num1, num2; num1 = stack.pop (); // ambil dua angka num2 = stack.pop (); switch (simbol) {case " +": stack.push (num2 + num1); merusak; case " -": stack.push (num2 - num1); merusak; case " *": stack.push (num2 * num1); merusak; case " /": stack.push (num2 / num1); merusak; default: break; }}} return stack.pop (); } / *** Traversal in-order diubah menjadi traversal berikutnya* / private static arrayList <String> transform (arrayList <String> arrayList) {stack <string> stack = stack baru <> (); ArrayList <String> result = ArrayList baru <> (); untuk (int index = 0; index <arraylist.size (); index ++) {string simbol = arraylist.get (index); if (isDigital (simbol)) {// Jika itu angka, itu adalah output langsung.add (simbol); } lain jika (simbol.equals (")")) {string tmp; while (!(tmp = stack.pop()).equals("(")) { // Stop after the match is successful result.add(tmp); } } else { if (stack.isEmpty()) { stack.push(symbol); continue; } String tmp = stack.peek(); while (outPriority(symbol) <= inPriority(tmp)) { //The Prioritas kurang dari prioritas dalam tumpukan, dan tumpukan selalu dirilis. } Hasil pengembalian;} / ** * Format pertama string ke dalam arraylist * @param src 3 * 5 + 8; ArrayList <> (); (! COMCHAR.TOSTRING (). TRIM (). Equals (")) {arrayList.Add (COMCHAR.TOSTRING (). TRIM ()); COMCHAR.DELETE (0, COMCHAR.Length ());} ArrayList.Add (ch +"); lanjutkan;} comchar. lampai (ch); (! COMCHAR.TOSTRING (). TRIM (). Equals ("")) {arrayList.Add (COMCHAR.TOSTRING (). TRIM ())} Return ArrayList; &&! "": return 1; default: return 0;}} private static int outpriority (string ch) {switch (ch) {case "+": case "-": return 3; case "*": case "/": return 5; case ")": return 1;Semua di atas adalah seluruh konten artikel ini. Saya berharap ini akan membantu untuk pembelajaran semua orang dan saya harap semua orang akan lebih mendukung wulin.com.