计算器Bug:仅输出输入算式而非计算结果求助
Let's break down why your calculator isn't working correctly and fix it step by step — there are a few key issues in the code that are causing the unexpected behavior:
Main Issues in the Original Code
- Scanner is closed too early: When you call
reader0.close()after reading the first input, it closes the underlyingSystem.instream. This means any subsequent Scanners (likereader2) won't be able to read input at all. - Incorrect operator capture: Your loop over the input string only keeps the last character in the
testvariable. So if you enter something like3+5,testends up being'5'instead of'+'— that's why your program never triggers the calculation logic. - String concatenation instead of numeric calculation: When you do
System.out.println(a+c), you're just joining two strings (like"3"+"5"becomes"35"), not adding the numbers. - Unused variables and commented-out logic: Variables like
bare declared but never used, and most of the calculation code is commented out, so even if the operator was captured, those operations wouldn't run. - Incorrect sqrt usage: You're passing the string
atoMath.sqrt()instead of the parsednumbervariable.
Step-by-Step Fixes
Don't close Scanners that use System.in (or use a single Scanner for all input)
ClosingSystem.inmakes it unavailable for future input. It's better to create one Scanner instance and reuse it throughout the program.Properly capture the operator and split the first number
Modify the loop to stop when it hits an operator, save that operator, and capture the first number correctly.Convert input strings to numeric types before calculation
UseDouble.parseDouble()on your input strings to get numeric values you can perform arithmetic with.Uncomment and fix the calculation logic
Restore the commented-out code and update it to use the parsed numeric values instead of strings.
Fixed Code
import java.util.Scanner; public class Calculator { public static void main(String[] args) { // Introduce the calculator System.out.println("Welcome to my calculator test"); System.out.println("Function inputs; + to add numbers, - to subtract numbers, * to multiply, / to divide, ^ to power, # to square root."); // Use a single Scanner for all input Scanner scanner = new Scanner(System.in); System.out.println("Please enter first number or expression (e.g., 3+ or # for sqrt)"); String input = scanner.nextLine(); char operator = ' '; StringBuilder firstNumberStr = new StringBuilder(); boolean operatorFound = false; // Parse the input to extract first number and operator for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if ((Character.isDigit(c) || c == '.') && !operatorFound) { firstNumberStr.append(c); } else if (c == '+' || c == '-' || c == '*' || c == '/' || c == '#' || c == '^') { operator = c; operatorFound = true; // Stop looping once we find the operator (for single-operator expressions) break; } else { System.out.println("Invalid input format. Please try again."); scanner.close(); return; } } // Handle square root case first if (operator == '#') { try { double number = Double.parseDouble(firstNumberStr.toString()); System.out.println("Square root result: " + Math.sqrt(number)); } catch (NumberFormatException e) { System.out.println("Error: Invalid number for square root."); } } else if (operator != ' ') { // Get second number System.out.println("Please enter second number"); String secondNumberStr = scanner.nextLine(); try { double num1 = Double.parseDouble(firstNumberStr.toString()); double num2 = Double.parseDouble(secondNumberStr); double result = 0; switch (operator) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': if (num2 == 0) { System.out.println("Error: Cannot divide by zero."); scanner.close(); return; } result = num1 / num2; break; case '^': result = Math.pow(num1, num2); break; default: System.out.println("ERROR: Unknown operator."); scanner.close(); return; } System.out.println("Result: " + num1 + " " + operator + " " + num2 + " = " + result); } catch (NumberFormatException e) { System.out.println("Error: Invalid number input."); } } else { System.out.println("ERROR: No valid operator found."); } scanner.close(); } }
Key Improvements in the Fixed Code
- Uses a single
Scannerinstance and closes it only at the end of the program. - Properly parses the input to capture the first number and operator correctly.
- Adds error handling for invalid numbers, division by zero, and unknown operators.
- Uses a
switchstatement for cleaner operator logic instead of multipleelse ifblocks. - Converts all input strings to
doublebefore performing arithmetic operations. - Provides clear output messages for results and errors.
内容的提问来源于stack exchange,提问作者c.jones

