Oracle Forms计算器中等号按钮多运算功能的编码实现咨询
Alright, let's get your equals button working smoothly. First, a quick missing piece you'll need: add a hidden text item (let's name it OPERATOR) to store which arithmetic operation the user picked (like '+', '-', '*', '/'). You already have logic on your operator buttons to save the Display value to Memory—now just update those buttons to also set the OPERATOR item to the corresponding symbol.
For example, your "+" button's WHEN-BUTTON-PRESSED code should look like this:
:MEMORY := :DISPLAY; :OPERATOR := '+'; :DISPLAY := ''; -- Clear display for the next number entry
Now, here's the full code for your equals button's WHEN-BUTTON-PRESSED trigger. It handles all basic arithmetic, data type conversion, and common errors like division by zero:
DECLARE v_memory_num NUMBER; v_display_num NUMBER; v_result NUMBER; v_operator VARCHAR2(1); BEGIN -- Fetch stored operator and convert display values to numeric types v_operator := :OPERATOR; v_memory_num := TO_NUMBER(:MEMORY); v_display_num := TO_NUMBER(:DISPLAY); -- Execute calculation based on the selected operator CASE v_operator WHEN '+' THEN v_result := v_memory_num + v_display_num; WHEN '-' THEN v_result := v_memory_num - v_display_num; WHEN '*' THEN v_result := v_memory_num * v_display_num; WHEN '/' THEN IF v_display_num = 0 THEN MESSAGE('Error: Cannot divide by zero!'); RAISE FORM_TRIGGER_FAILURE; END IF; v_result := v_memory_num / v_display_num; ELSE MESSAGE('No valid operator selected!'); RAISE FORM_TRIGGER_FAILURE; END CASE; -- Update display with result and reset calculation state :DISPLAY := TO_CHAR(v_result); :MEMORY := ''; :OPERATOR := ''; EXCEPTION WHEN INVALID_NUMBER THEN MESSAGE('Invalid numeric value entered!'); RAISE FORM_TRIGGER_FAILURE; WHEN OTHERS THEN MESSAGE('Unexpected error: ' || SQLERRM); RAISE FORM_TRIGGER_FAILURE; END;
Key Details to Keep in Mind:
- Data Conversion: Since
MEMORYandDISPLAYare character-based items, we useTO_NUMBER()to convert their values for calculations, thenTO_CHAR()to put the result back into the display. - Error Handling: Explicitly catches division by zero, invalid number entries (in case something unexpected slips into the display), and general exceptions to prevent the form from crashing.
- State Reset: After calculating, we clear
MEMORYandOPERATORso the user can start a new calculation immediately.
Double-check that your MEMORY, DISPLAY, and OPERATOR items are properly configured: MEMORY and OPERATOR should be set to Hidden in their properties, and DISPLAY should be a read-only text item (since only numeric/operator buttons should update it).
内容的提问来源于stack exchange,提问作者Ramiz Tariq

