如何为Java累加计算器添加循环直至用户输入退出指令?
Continuous Running Calculator Fix
Got it, let's tweak your code so it runs non-stop until you type "exit" or "e" to quit. Here's the revised version with clear explanations of the changes:
Revised Code
import java.util.Scanner; public class Main { public static void main(String[] args) { System.out.println("Welcome to the persistent calculator!"); System.out.println("Starting result: 0"); System.out.println("Enter operations like '[operator] [number]' (e.g., - 7), or type 'exit'/'e' to close."); Scanner scanner = new Scanner(System.in); int currentResult = 0; // Loop indefinitely until exit command is received while (true) { System.out.print("> "); String input = scanner.nextLine().trim().toLowerCase(); // Check if user wants to exit if (input.equals("exit") || input.equals("e")) { System.out.println("Closing calculator... See you!"); break; } // Split input into operator and number components String[] inputParts = input.split("\\s+"); if (inputParts.length != 2) { System.out.println("Oops, invalid input! Use format like '+ 10' or type 'exit' to quit."); continue; } String operator = inputParts[0]; int rightOperand; try { rightOperand = Integer.parseInt(inputParts[1]); } catch (NumberFormatException e) { System.out.println("That's not a valid number! Please enter an integer."); continue; } // Calculate and update the result try { currentResult = compute(currentResult, operator, rightOperand); System.out.println("Current result: " + currentResult); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } } scanner.close(); } private static int compute(int left, String op, int right) { // Note: Multiplication has potential issues, not addressed per requirement switch (op.charAt(0)) { case '+': return left + right; case '-': return left - right; case '*': return left * right; case '/': // Added division by zero check to avoid crashes if (right == 0) { throw new IllegalArgumentException("Cannot divide by zero!"); } return left / right; default: throw new IllegalArgumentException("Unknown operator: " + op); } } }
Key Improvements Explained
- Continuous Loop: Used a
while(true)loop that runs forever until the user enters "exit" or "e"—this triggers abreakto exit the loop and close the program. - Better Input Handling: Reads full lines of input instead of using
next()/nextInt()directly, which avoids errors when the user types an exit command instead of an operator/number pair. - Error Resilience: Added checks for invalid input formats, non-integer values, unknown operators, and division by zero to make the calculator more user-friendly and crash-resistant.
- Persistent State: The
currentResultvariable keeps track of the last calculation result, which is automatically used as the left operand for every subsequent operation. - Clear Prompts: Added simple instructions and prompts to guide users on how to interact with the tool.
Quick Note
As requested, the multiplication logic is kept in its original state (with potential issues unaddressed).
内容的提问来源于stack exchange,提问作者Ichmag17
相关产品推荐
相关产品推荐

